1

I have a problem with a javascript function. It runs by itself when the page loads even if it`s set to run .onchange

I have a select that looks like this:

<select name="make_brand" id="make_brand" class="form_tag dispB width_full">
     <option value="" selected disabled>Please select</option>
     <option value="1">Audi</option>
     <option value="2">BMW</option>
     <option value="3">Mercedes-Benz</option>
</select>

And my js looks like this:

// defining select fields
var brand = document.getElementById("make_brand");

// get values
function getSelectedValue(element, show_mark){
     return element.options[element.selectedIndex].value;
}

// on select change
brand.onchange = getSelectedValue(brand, true);

When I refresh the page, the function runs automatically and I don`t know why. Can anyone help me with this? I want the function to run on select change.

  • 6
    You're setting the event handler to the return value of `getSelectedValue`, rather than the function itself. I feel like this ought to have a duplicate somewhere, but haven't found a good one yet. – James Thorpe Feb 04 '16 at 10:47

3 Answers3

0

Your code is running your getSelectedValue function and then setting setting brand.onchange to it's return value. You can only set event handlers in that way if you do not need parameters.

You have two options for passing parameters to dom element events:

You can make an anonymous function like so:

brand.onchange = function(event){
    return getSelectedValue(event.target, true);
}

Or you can add your event to your html element directly:

<select name="make_brand" onchange="getSelectedValue(this,true)" ...
cronoklee
  • 6,482
  • 9
  • 52
  • 80
0

this should do...

<html>
<head>
<script>

function init(){
var brand = document.getElementById("make_brand");
// on select change
brand.addEventListener("change", function(){getSelectedValue(brand, true)});

}

 // get values
function getSelectedValue(element, show_mark){
     return element.options[element.selectedIndex].value;
}

</script>
</head>
<body onLoad = "init()">
<select name="make_brand" id="make_brand" class="form_tag dispB width_full">
 <option value="" selected disabled>Please select</option>
 <option value="1">Audi</option>
 <option value="2">BMW</option>
 <option value="3">Mercedes-Benz</option>
</select>
</body>
</html>

you have to let the document load before adding a listener to an element in the document. Notice the body tag, I called my init() function within onLoad.

Ayo K
  • 1,719
  • 2
  • 22
  • 34
-2

brand.onchange should be a function like this : brand.onchange = function(event){ getSelectedValue(brand, true); }