Jemru
Jemru

Reputation: 2119

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.

Upvotes: 0

Views: 3687

Answers (2)

James Allardice
James Allardice

Reputation: 165951

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.

Upvotes: 3

Michael Robinson
Michael Robinson

Reputation: 29498

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.

Upvotes: 5

Related Questions