سؤال

Compare the code on

jsfiddle

HTML

<select name="client_select" id="client_select">
<option value="Name not listed">Name not listed</option>
<option value="1">abc company</option>
</select>
<span id="client_add"><input type="text" name ="" value="field1"/></span>

Javascript

document.getElementById("client_select").onchange = 
function (e) {
if (this.value == 'Name not listed') {
    document.getElementById("client_add").style.display="";
    } else {
        document.getElementById("client_add").style.display="none";    
    }
};

to

my site

<script>
document.getElementById("client_select").onchange = 
function (e) {
    if (this.value == 'Name not listed') {
        document.getElementById("client_add").style.display="";
    } else {
document.getElementById("client_add").style.display="none";    
    }
};
</script>
<select name="client_select" id="client_select">
<option value="Name not listed">Name not listed</option>
    <option value="1">abc company</option>
</select>
<span id="client_add"><input type="text" name ="" value="field1"/></span>

Solution:

Run javascript after elements have been loaded into the clients DOM.

Do one of the following:

  • Load javascript AFTER html elements

  • Use a onLoad() to wrap script

  • With jQuery use $( document ).ready(function() { }

هل كانت مفيدة؟

المحلول

The element is not available when you're trying to use it, as it hasn't been loaded in the DOM yet.

Move the script after the elements

<select name="client_select" id="client_select">
    <option value="Name not listed">Name not listed</option>
    <option value="1">abc company</option>
</select>
<span id="client_add"><input type="text" name ="" value="field1"/></span>

<script>
    document.getElementById("client_select").onchange = function(e) {
        if (this.value == 'Name not listed') {
            document.getElementById("client_add").style.display = "";
        } else {
            document.getElementById("client_add").style.display = "none";
        }
    };
</script>

I would also encourage the use of addEventListener

نصائح أخرى

An easy solution is to wrap your script in a window.onload function like:

window.onload = function(){
    // Do things here...
};

Or if jQuery is available:

$(function(){
    // Do things here...
});
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top