Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to trigger jQuery change event on dropdown with same value

How can I trigger the jQuery change event every time even when user selects the same value? I need a refresh effect e.g if a user select Lawyer and it alert hello then again user select Lawyer from the dropdown and it should alert hello. How can I achieve it? Following is the code.

jQuery

function filterPullDown () {
    alert('hello');
}
$(".businessTypePullDown").change(filterPullDown);

HTML

<select class="businessTypePullDown">
    <option value="" disabled selected>Business Type</option>
    <option value="1">General</option>
    <option value="2">Lawyer</option>
    <option value="3">Software Development</option>
    <option value="4">Auto-repair</option>
</select>

Link to fiddle

like image 491
Superman Avatar asked Jan 23 '15 10:01

Superman


2 Answers

This should work. Its a combination of flags and click events. It will always get triggered when you click on an option.

<select class="businessTypePullDown">
    <option value="" disabled selected>Business Type</option>
    <option value="1">General</option>
    <option value="2">Lawyer</option>
    <option value="3">Software Development</option>
    <option value="4">Auto-repair</option>
</select>
(function () {

  var filterPullDown = function() {
         alert('clicked');   
    }
    var flag = false;
    $(".businessTypePullDown").click(function () {
        if (flag) {
            filterPullDown()
        }
        flag = !flag;
    });

    $(".businessTypePullDown").focusout(function () {
        flag = false;
    });
}());
like image 171
skay- Avatar answered Sep 18 '22 12:09

skay-


I think @MrUpsidown had just answered the question without knowing it! Why not add the event handler on the option element itself rather than the outer select element attribute.

Going back to Superman's code, use this:

$(".businessTypePullDown option").on("click", filterPullDown);

That will invoke the 'filterPullDown' function EVERY time, no matter whether the same value is selected.

like image 29
z1md4wg Avatar answered Sep 18 '22 12:09

z1md4wg