开发者

Firefox will not validate form data

开发者 https://www.devze.com 2023-04-12 17:54 出处:网络
The following simple form with javascript with onclick button does not work in Firefox (I have version 7) but works开发者_开发技巧 fine in IE, Chrome, and Safari.

The following simple form with javascript with onclick button does not work in Firefox (I have version 7) but works开发者_开发技巧 fine in IE, Chrome, and Safari. What am I missing?

<head>
<script type="text/javascript">
    function result() {
        alert(calc.input.value);
        }
</script>

</head>
<body>

<form name="calc" action="">
    <input class="cInput" type="text" name="input" size="16" /><br/>
    <input type="button" class="cButton" name="seven" value="1" onclick="calc.input.value += '1'" />
    <input type="button" class="cButton" name="equal" value="=" onclick="result()" /><br/>
</form>
</body>


<script type="text/javascript">
    var calc;
    function result() {
        calc = document.forms['calc'];
        alert(calc.input.value);
        }
</script>


What am I missing?

You are missing that IE adds element names and ids as global variables. Some other browsers in certain conditions (sometimes requiring the document to be in quirks mode) will copy that habbit, some wont.

So in IE (and some others) the form name calc is a global variable referencing the form and in other browsers it isn't.

The method in Dunuyadnd's answer is a robust, cross-browser way to get a reference to the form. The formal access method is:

document.forms['calc'];

Named form controls can accessed similarly:

document.forms['calc'].elements['input'];

or

document.calc.input;

Be careful with giving controls names that are the same as tags, it is a bit confusing. Also, if there is more than one control with the same name, you will get an HTML collection rather than a single element.

You may want to read about HTMLForms and their related elements.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号