Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 575
B. Clay Shannon-B. Crow Raven Avatar asked Jul 01 '13 21:07

B. Clay Shannon-B. Crow Raven


1 Answers

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

like image 119
PSL Avatar answered Oct 12 '22 11:10

PSL