简体   繁体   中英

Access form element through javascript - what's the correct way?

I am developing an asp.net application and i want to make it compatible with all 3 major browsers (Internet Explorer, Firefox, Chrome) at least.

In some pages i need to access the form elements through javascript. What is the correct way to do this so that it works on all browsers?

I have been doing something like this

document.forms[0].elements["nroErros"].value

to access my "nroErros" hidden field for instance and even though this works on IE, it doesn't seem to work correctly on Firefox.

So, the question is, what is the correct way to make it work always?

Sure fire way would be to give them an ID and use document.getElementById or the jQuery $ selector.

Use:

document.getElementById('nroErros');

You may need to account for ASP.NET name mangling, in which case you would do:

document.getElementById('<%= nroErros.ClientID %>');

I would suggest you to use document.getElementById('nroErros').value

It works for me: http://jsfiddle.net/6GJsy/

I believe this is the most cross-browser solution (if you replace elements[elementName] with elements[elementNumber] ).

However, as alternatives you could use:

document.formname.elementname.value; // simplest IMO
document.forms[formnumber].elements[elementnumber].value; // most cross-browser solution
document.forms[formname].elements[elementname].value;
document.getElementById(elementId).value;
document.getElementByName(elementName).value; // not supported in some browsers

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM