Jquery event when user makes selection in dropdown

前端 未结 4 520
北荒
北荒 2020-12-29 12:17

I have a drop down list. In Jquery what is the event I would use when the user makes a selection.

The id of the dropdown is drp1

I tried the following but di

相关标签:
4条回答
  • 2020-12-29 12:57

    Use the change() event:

    $("#ddrp1").change(function() {
        // Pure JS
        var selectedVal = this.value;
        var selectedText = this.options[this.selectedIndex].text;
    
        // jQuery
        var selectedVal = $(this).find(':selected').val();
        var selectedText = $(this).find(':selected').text();
    });
    

    In jQuery 1.7, you can use .on()

    $("#ddrp1").on("change", function() {
        // Pure JS
        var selectedVal = this.value;
        var selectedText = this.options[this.selectedIndex].text;
    
        // jQuery
        var selectedVal = $(this).find(':selected').val();
        var selectedText = $(this).find(':selected').text();
    }​​​​);​
    

    Here's a working jsFiddle using on()

    0 讨论(0)
  • 2020-12-29 13:04

    Use jQuery change event handler.

    $("#ddrp1").change(function(){
        //selection changed
        alert(this.value);//this will give the selected option's value
        alert($(this).find(':selected').text());//this will give the selected option's text
    });
    

    Alternative way to bind change event handler is.

    $("#ddrp1").bind('change', function(){
    
    });
    
    0 讨论(0)
  • 2020-12-29 13:08

    What you want is onchange event which can be written as

     $("#ddrp1").change (function () { 
     });
    
    0 讨论(0)
  • 2020-12-29 13:20

    You need to use change().

    jQuery change event occurs when the value of an element is changed.

    This event is limited to input elements, textarea boxes and select elements.

    $("#ddrp1").change (function () { 
    
         var getText = $(this).find(':selected').text();
         alert (getText); // show the text value of the selected element ...
    
     });
    
    0 讨论(0)
提交回复
热议问题