Skip to content Skip to sidebar Skip to footer

Select On Change Not Working Correct

I have a select option that calls a function that needs to be triggered on change. But now it's triggered when the page is loaded and on change. See below: $(function () { $('sel

Solution 1:

Currently You are calling uren function when you are using uren("Zondag"). You should use an anonymous function as event handler and call uren function.

Use it like

$('select[id^="iZondagbegin_"]').on('change', uren("Zondag"));

To:

$('select[id^="iZondagbegin_"]').on('change', function () {
    uren("Zondag");
});

I would recommend, You to use data-* attributes to store what need to be passed to change event handler.

Example:

HTML, Here Added a cooom class mySelect

<selectclass="mySelect" id="iZondagbegin_1" data-value="Zondag"> .... </select>
<selectclass="mySelect" id="iMaandagBegin_" data-value="Maandag"> .... </select>

Script

$('.mySelect').on('change', function () {
    uren($(this).data('value'));
});

Solution 2:

There's already two answers that point out your issue; an alternative solution is to let jQuery handle contexts with $.proxy:

$('select[id^="iZondagbegin_"]').on('change', $.proxy(uren, null, "Zondag");

More info here

Solution 3:

Please change all lines like:

$('select[id^="iZondagbegin_"]').on('change', uren("Zondag"));

To:

$('select[id^="iZondagbegin_"]').on('change', uren);

and:

<select id="iZondagbegin_...." data-value="Zondag">.....</select>

and:

functionuren() {
     var value = $(this).data('value');
     //.....
}

Or better still, use a common class, .myclass say, on all the select elements and do the binding with one statement.

$('select.myclass').on('change', uren);
.....
<select id="iZondagbegin_...." data-value="Zondag"class="myclass">.....</select>
.....
function uren() {
     varvalue = $(this).data('value');
     //.....
}

When you pass arguments like that or when you provide (), the function will be invoked immediately. You don't want that.

Post a Comment for "Select On Change Not Working Correct"