简体   繁体   中英

What event fires when item in HTML select/dropdown list is selected?

I want to respond to the user selecting an item in a select element. Yet this jQuery:

$('#platypusDropDown').select(function () {
    alert('You selected something');
});

...does nothing. It shows no alert, although jsFiddle sees it as valid jQuery.

The Click event works, but it's too fast - it fires on clicking the select element, prior to making a selection.

Of course, I really want to do something like:

$('#platypusDropDown').select(function () {
    var selection = $('platypusDropDown').val;
    $.getJSON('platypus.json', selection, data() {
        // . . .
    });
});

The HTML:

<select id="platypusDropDown">
    <option value="duckbill">duckbill</option>
    <option value="duckbillPlatypus">duckbillPlatypus</option>
    <option value="Platypus">Platypus</option>
    <option value="Platypi">Platypi</option>
</select>

You need to use change event

$('#platypusDropDown').change(function () {
    var selection = this.value; //grab the value selected
    $.getJSON('platypus.json', selection, data() {
    . . .
    });
});

Fiddle

Plus $('platypusDropDown').val here val should be val() and you dont need to create a jquery object again over the element, this inside the handler represents DOM element (select on which the event is bound to) and you can directly access the value with this.value or $(this).val()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM