Development Tip

크롬의 선택 옵션 요소에 대한 클릭 이벤트

yourdevel 2020. 11. 30. 20:07
반응형

크롬의 선택 옵션 요소에 대한 클릭 이벤트


Chrome다음과 같은 문제가 있습니다.

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

items.each(function(){

    $(this).click(function(){

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

click이벤트는 화재하지 않는 것 Chrome,하지만 작동합니다 Firefox.

내가 할 수있을 싶어 clickA의 option내가 요소 대신 다른 종류의 일을하는 경우, 콤보에서 요소라고 할 수 있습니다 <li>그것을 잘 작동합니다. 어떤 아이디어? 감사.


클릭 이벤트가 옵션에서 유효하지 않다고 생각합니다. 그러나 선택한 요소에서는 유효합니다. 이것을 시도하십시오 :

$("select#yourSelect").change(function(){
    process($(this).children(":selected").html());
});

를 사용하여 이벤트를 직접 호출하더라도 다른 방법으로 이룰 수 있습니다 <select>.

JS 부분 :

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

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

HTML 부분 :

<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>

선택을 변경하고 업데이트하는 쉬운 방법은 이것입니다.

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

또 다른 예:

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

또 다른 예:

$("#select_element_selector").val('value').trigger('chosen:updated');

다음이 저에게 효과적이라는 것을 알았습니다. 대신 클릭시 사용, 예 : 변경시 사용 :

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

       //your code here

}));

I've had simmilar issue. change event was not good for me because i've needed to refresh some data when user clicks on option. After few trials i've got this solution:

$('select').on('click',function(ev){
    if(ev.offsetY < 0){
      //user click on option  
    }else{
      //dropdown is shown
    }
});

I agree that this is very ugly and you should stick with change event where you can, but this solved my problem.


<select id="myselect">
    <option value="0">sometext</option>
    <option value="2">Ready for Review</option>
    <option value="3">Registration Date</option>
</select>

$('#myselect').change(function() {
    if($('#myselect option:selected').val() == 0) {
    ...
    }
    else {
    ...
    }
});

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...


Looking for this on 2018. Click event on option tag, inside a select tag, is not fired on Chrome.

Use change event, and capture the selected option:

$(document).delegate("select", "change", function() {
    //capture the option
    var $target = $("option:selected",$(this));
});

Be aware that $target may be a collection of objects if the select tag is multiple.


I use a two part solution

  • Part 1 - Register my click events on the options like I usually would
  • Part 2 - Detect that the selected item changed, and call the click handler of the new selected item.

HTML

<select id="sneaky-select">
  <option id="select-item-1">Hello</option>
  <option id="select-item-2">World</option>
</select>

JS

$("#select-item-1").click(function () { alert('hello') });
$("#select-item-2").click(function () { alert('world') });

$("#sneaky-select").change(function ()
{
   $("#sneaky-select option:selected").click();
});

What usually works for me is to first change the value of the dropdown, e.g.

$('#selectorForOption').attr('selected','selected')

and then trigger the a change

$('#selectorForOption').changed()

This way, any javascript that is wired to


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);
});

Since $(this) isn't correct anymore with ES6 arrow function which don't have have the same this than function() {}, you shouldn't use $( this ) if you use ES6 syntax.
Besides according to the official jQuery's anwser, there's a simpler way to do that what the top answer says.
The best way to get the html of a selected option is to use

$('#yourSelect option:selected').html();

You can replace html() by text() or anything else you want (but html() was in the original question).
Just add the event listener change, with the jQuery's shorthand method change(), to trigger your code when the selected option change.

 $ ('#yourSelect' ).change(() => {
    process($('#yourSelect option:selected').html());
  });

If you just want to know the value of the option:selected (the option that the user has chosen) you can just use $('#yourSelect').val()


Workaround:

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

참고URL : https://stackoverflow.com/questions/1402227/click-event-on-select-option-element-in-chrome

반응형