Bind click event on select option

前端 未结 7 1267
长情又很酷
长情又很酷 2021-01-17 21:54

I\'ve got a problem making a click event on an HTML option element work.

Even a simple console.log(\'hello!\'); won\'t work.

相关标签:
7条回答
  • 2021-01-17 22:01

    In my case following code works

    $('#myItem').change(function(){
                //do somthing
    })
    
    0 讨论(0)
  • 2021-01-17 22:03

    Sample example will show how to change dropdown values and color for the OPTION on click or change of select

    HTML:

    <select name="options">
          <option value="1">Red</option>
          <option value="2" selected="1">Green</option>
          <option value="3">Blue</option>
    </select>
    

    jQuery:

    $("select").on("click", function () {
        debugger;
        var sVal = $(this).val();
        $(this).css("background-color", "red");
        $(this).find("option").css("background", "white");
        $(this).find('option:selected').css("background-color", "red");
        $("input").val($(this).val());
    });
    

    Demo

    0 讨论(0)
  • 2021-01-17 22:03

    because change not good enough for me and I didn't find a way to trigger the option click what I did is

     $('#mySelect').click(function () {
            if ($(this).attr('optionclick') == '1') {
                 $(this).attr('optionclick', '0');
            }
            else {
                 $(this).attr('optionclick', '1');
            }
      });
    
    0 讨论(0)
  • 2021-01-17 22:05

    I would suggest you to use .on() instead of .bind().

    $('#mySelect').on('change', function(){
      var $this = $(this),
          $value = $this.val();
    
      alert($value);
    
    });
    

    jsFiddle

    0 讨论(0)
  • 2021-01-17 22:07

    Check this js fiddle --

    http://jsfiddle.net/4W826/

    HTML

    <select id="mySelect">
                   <option value="volvo">Volvo</option>
                   <option value="saab">Saab</option>
                   <option value="mercedes">Mercedes</option>
                   <option value="audi">Audi</option>
           </select>  
    

    JQUERY

    $('#mySelect').bind('click', function(){
    alert('hi!');
    });
    

    Change from Click to Change

    0 讨论(0)
  • 2021-01-17 22:18

    You can bind using .on() by giving <select> id. In general, change is the event called upon <select>.

    So, there is no need to mention option while binding event.

    $(document).on('change','#mySelect', function(){<br>
        console.log('hi!');
    });
    

    OR

    $('#mySelect').bind('change',function(){<br>
        console.log('hi!');
    });
    
    0 讨论(0)
提交回复
热议问题