简体   繁体   中英

document.getElementById is null

I have the following JavaScript working in IE, but not on Chrome and Firefox. Here is the code:

<script type="text/javascript">
jQuery(document).ready(function() {

jQuery('#applicationSelect').change(function() {
document.getElementById('dropdown').value = "APPLICATION";
});

});
</script>

<input type="hidden" name="dropdown" value="" />

When I look in Firebug, the code errs:

document.getElementById("dropdown") is null
document.getElementById('dropdown').value = "APPLICATION";

I need your advice. Thank you in advance.

If you're using jQuery already, why not use it to set your input value:

$('#dropdown').val('APPLICATION');

And as others noted, your input's id was not 'dropdown'.

Also, note that to one may use $ in place of jQuery in most use-cases.

The problem is that your input element doesn't have an id ! Change name to id , or add an id too:

<input type="hidden" name="dropdown" id="dropdown" value="" />

Alternatively, if you don't want to add an id , you could use getElementsByName (which doesn't work very well cross-browser), or you could use a jQuery attribute selector:

$("input[name='dropdown']").val("APPLICATION");

Update

I just noticed that you said in your question that it was working in IE. That means you must be using a pretty old version of IE, because getElementById in IE7 and below incorrectly selects elements by name , as well as id .

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