2

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() { }

logo3801
  • 85
  • 9
  • Am I missing any dependencies that jsfiddle has by default? I checked and jsfiddle doesn't seem to be including anything. – logo3801 May 06 '14 at 17:45
  • The object wasn't loaded in the DOM when I was trying to find it with Javascript. Solution script after elements. – logo3801 May 06 '14 at 17:51

2 Answers2

1

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

adeneo
  • 312,895
  • 29
  • 395
  • 388
1

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...
});
ncksllvn
  • 5,699
  • 2
  • 21
  • 28