2

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!

2 Answers 2

4

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>

Sign up to request clarification or add additional context in comments.

2 Comments

Don't you hate it when that happens??? I knew it was something silly I had missed just staring and staring at the code.
A professional can make the same mistake , that's why we like to code you make the mistake and you have the option to fix it yourself as a champion :D
0

Your Javascript has:

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.