Derek Erb
Derek Erb

Reputation: 130

Javascript onchange function executes onload but not onchange

My onchange function for this form select is executing onload but not when changing the selection in the form. I've tried using both onload and onclick.

I'm obviously only at the debugging implementation stage and will have it do other stuff once it works.

HTML:

<select case="sel1" name="Sort1" id="Sort1">
    <option value="0">Fred</option>
    <option value="1">Ginger</option>
    <option value="2">Judy</option>
    <option value="3">Gene</option>
</select>

JavaScript:

window.onload = function() {
    document.getElementById('Sort1').onchange = ChgSort();
}

function ChgSort() {
    alert(document.getElementById('Sort1').value);
}

When I load the page I get the alert popup with the current select value of 0. But when I click on the select field and change the option nothing happens.

I'm sure, and hope, it's something silly and stupid and I've just been staring and debugging the same function too long...

Help!

Upvotes: 2

Views: 1652

Answers (2)

hurtbox
hurtbox

Reputation: 386

Your Javascript has:

window.onload = function() {
    document.getElementById('Sort1').onchange = ChgSort();
}

The window.onload should be changed to window.onchange and it should work

Upvotes: 0

mostafa tourad
mostafa tourad

Reputation: 4388

You will need to change on line this

        document.getElementById('Sort1').onchange = ChgSort();

to this

        document.getElementById('Sort1').onchange = ChgSort;

onchange should be function not the returned value look at the example below

window.onload = function() {
    document.getElementById('Sort1').onchange = ChgSort;
}

function ChgSort() {
    alert(document.getElementById('Sort1').value);
}
<select case="sel1" name="Sort1" id="Sort1">
    <option value="0">Fred</option>
    <option value="1">Ginger</option>
    <option value="2">Judy</option>
    <option value="3">Gene</option>
</select>

Upvotes: 4

Related Questions