Sunday, March 20, 2011

How to catch the event of change of <select > with jQuery?

<select id="target">
<option value="1">item1</option>
<option value="2">item2</option>
<option value="3">item3</option>
</select>

Say,I want to do some processing according to selected value.

From stackoverflow
  • $('#target').change( function() {
       $(this).find(":selected").each(function () {
                console.log( $(this).val() );
        });
     });
    
  • $("#target").change( function() {
      var selectedOption = $("#target option:selected");
      var selectedValue = selectedOption.val();  // gets the selected value
      var selectedText = selectedOption.text();  // gets the selected text
    });
    
    David Andres : Please add details to your answer concerning how to acquire the selected value within the event handler (it's mentioned in the OP).
    RSolberg : your initial selector appears to have some random characters ']
    CMS : Also, replace `selected` by `selectedOption` or the opposite
    rahul : Thanks. Fixed the typo.
  • $("#target").change( function() {
        alert($("#target option:selected").val());
    });
    

    You may also need to consider this as well if the person does not change the option, but simply clicks on the drop down and selects the same item:

    $("#target option").click( function() {
         alert($("#target option:selected").val());
    });
    
  • You can get the selected value and text simply by:

    $("#target").change(function() {
      var selectedValue = $(this).val(),
          selectedText = $('option:selected', this).text();
      // ...
    });
    

0 comments:

Post a Comment