Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery select change event when selecting the same value

How can I handle the collapse event of a select, or trigger the change event even if the selected option did not change ?

I need to have this for a search engine, where the mascot will still move if the option that was selected is the same. The search engine is on this page : http://www.marocpneus.com

For example, if you go ahead and click on the first select "Type de véhicule" and choose "Tourisme" which was already selected, the character will not move to the second select. However if you do change "Tourisme" to one of the other values, the character will indeed move using the classic jQuery change event.

like image 439
Yassir Ennazk Avatar asked Mar 16 '13 17:03

Yassir Ennazk


1 Answers

Ok, after some research, it looks like select option clik cannot been fired due to browsers incomptability (look this SO question: Event attached to Option node not being fired)

... but we can simulate the click, to make a workaround, XD, you have the fiddle here: http://jsfiddle.net/H9gg5/3

Js

$('select.click_option').click(function() {
    if ( $(this).data('clicks') == 1 ) {
        // Trigger here your function:    
        console.log('Selected Option: ' + $(this).val() );
        $(this).data('clicks', 0);
    } else {
        console.log('first click');
        $(this).data('clicks', 1);
    }
});

$('select.click_option').focusout( function() {
    $(this).data('clicks', 0);
});

Html

<select class="click_option">
      <option value="1"> Selected 1 </option>
      <option value="2"> Selected 2 </option>
</select>

What does it do? Well, we know we have selected an option (even the same option) because we click twice over the select, so, just count the number of clicks, and when it comes after a previous click, trigger it, XD. The code also handles the lose of focus, because if you click out of the select, it will close with clicks = 1 and you have to reset it.

I've added a class to the select, for triggering only the function when the user clicks the select that you want.

Hope it helps, regards!

like image 110
Federico J. Avatar answered Sep 28 '22 02:09

Federico J.