Click event on select option element in chrome

2018-12-31 15:38发布

I'm having a problem in Chrome with the following:

var items = $("option", obj);  

items.each(function(){

    $(this).click(function(){

        // alert("test");
        process($(this).html());
        return false;
    });
});

The click event doesn't seem to fire in Chrome, but works in Firefox.

I wanna be able to click on a option element from a combo, if I do instead another kind of element, lets say <li> it works fine. Any ideas? Thanks.

13条回答
后来的你喜欢了谁
2楼-- · 2018-12-31 16:12

Workaround:

$('#select_id').on('change', (function() { $(this).children(':selected').trigger('click'); }));

查看更多
与风俱净
3楼-- · 2018-12-31 16:13

I found that the following worked for me - instead on using on click, use on change e.g.:

 jQuery('#element select').on('change',  (function() {

       //your code here

}));
查看更多
公子世无双
4楼-- · 2018-12-31 16:15

The easy way to change the select, and update it is this.

// BY id
$('#select_element_selector').val('value').change();

another example:

//By tag
$('[name=selectxD]').val('value').change();

another example:

$("#select_element_selector").val('value').trigger('chosen:updated');
查看更多
查无此人
5楼-- · 2018-12-31 16:15

Maybe one of the new jquery versions supports the click event on options. It worked for me:

$(document).on("click","select option",function() {
  console.log("nice to meet you, console ;-)");
});

UPDATE: A possible usecase could be the following: A user sends a html form and the values are inserted into a database. However one or more values are set by default and you flag this automated entries. You also show the user that his entry is generated automatically, but if he confirm the entry by clicking on the already selected option you change the flag in the database. A rare sue case, but possible...

查看更多
何处买醉
6楼-- · 2018-12-31 16:21

We can achieve this other way despite of directly calling event with <select>.

JS part:

$("#sort").change(function(){

    alert('Selected value: ' + $(this).val());
});

HTML part:

<select id="sort">
    <option value="1">View All</option>
    <option value="2">Ready for Review</option>
    <option value="3">Registration Date</option>
    <option value="4">Last Modified</option>
    <option value="5">Ranking</option>
    <option value="6">Reviewed</option>
</select>
查看更多
旧时光的记忆
7楼-- · 2018-12-31 16:23

I know that this code snippet works for recognizing an option click (at least in Chrome and FF). Furthermore, it works if the element wasn't there on DOM load. I usually use this when I input sections of inputs into a single select element and I don't want the section title to be clicked.

$(document).on('click', 'option[value="disableme"]', function(){
    $('option[value="disableme"]').prop("selected", false);
});
查看更多
登录 后发表回答