jQuery select change event when selecting the same value

坚强是说给别人听的谎言 提交于 2019-11-28 01:21:04
Chococroc

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!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!