Jeff
Jeff

Reputation: 4413

Javascript onChange dropdown

I am trying to call a javascript function onChange of an HTML Select.

HTML Doc:

<select name="network" onChange="test(this)">
    <option value="net1">Net1</option>
    <option value="net2">net2</option>
</select>
<script>
    alert("test");
    var URLArray = [];
    function test(str){
        alert("test");
    }
</script>

I get the first alert, but not the second one. What am I missing?

EDIT: The code actually works, but for whatever reason, I cannot use the separate panes in JSFiddle. Any thoughts on that?

Upvotes: 2

Views: 11797

Answers (4)

magritte
magritte

Reputation: 7636

When jsFiddle runs your code, it wraps it in a closure like this:

<script type='text/javascript'>//<![CDATA[ 
window.onload=function(){
    alert("test");
    var URLArray = [];
    function test(str){
        alert("test");
    }
}//]]>  
</script>

So the function you defined "test", is never available as a global function, therefore not accessible by the inline javascript which you placed on the select tag.

I strongly suggest you learn to use jQuery instead to attach your event handlers like this:

<select name="network">
    <option value="net1">Net1</option>
    <option value="net2">net2</option>
</select>

$(function () {
    console.log("oh look, the document is ready");

    $("[name=network]").change(function () {
        console.log("now my code is groovy, but i might want to use an id rather than name selector"); 
    });
});

Upvotes: 2

Narxx
Narxx

Reputation: 8299

As Panayot said, your code is OK, but I'd rather use console.log() instead of alert. It's much easier to view on the console than following alerts.

<select name="network" onChange="test(this)">
    <option value="net1">Net1</option>
    <option value="net2">net2</option>
</select>
<script>
    console.log("test1")
    var URLArray = [];
    function test(str){
        console.log("test2");
    }
</script>

Upvotes: 0

Mehdi Karamosly
Mehdi Karamosly

Reputation: 5428

try to move your script above your first call like below:

<script>
    alert("test");
    var URLArray = [];
    function test(str){
        alert("test");
    }
</script>


<select name="network" onChange="test(this)">
    <option value="net1">Net1</option>
    <option value="net2">net2</option>
</select>

This is the jsfiddle as you see I set the javascript to be put in the header.

Upvotes: 0

Panayot Karabakalov
Panayot Karabakalov

Reputation: 3179

Your script is Ok, you just put the same value ("test") for both alert.

<script>
    alert("test1");
    var URLArray = [];
    function test(str){
        alert("test2");
    }
</script>

Or maybe the final goal is this...

function test(elm){
    alert(elm.value);
}

Upvotes: 0

Related Questions