Reputation: 5568
How do I write a click event in jQuery that will capture the value of a dropdown? I have:
var select = $('select #dealerName');
$(function {
select.click(function {
alert( $('#dealerName').val() );
});
});
I'm just trying to get the value -- that's why I'm alerting it. What would the click function look like? The id on my dropdown is "dealerName". The above is not alerting anything.
Upvotes: 0
Views: 5925
Reputation: 488374
Five things:
Unless your javascript code is at the bottom of the document, you need to include all your jQuery inside $(function() { }); - as it is right now it will try to find your select before the DOM is ready to be accessed.
If the ID of the <select>
element is #dealerName
, your jQuery selector is going to be $('#dealerName') - as it is right now you are looking for a descendant to a <select>
with the ID specified. You also don't want to do select#dealerName as IDs are meant to be unique and specifiying the tag is only going to slow jQuery down.
click
will fire as soon as someone clicks on the select as opposed to when a new option is chosen. You probably want change
Not too big of a deal, but there is a slightly popular convention to name variables that refer to jQuery wrappers with a $
at the beginning to be able to quickly tell what is a jQuery wrapped.
Inside an event call you can quickly reference the element in question with this
So a working example would be:
$(function() {
$('#dealerName').change(function() {
alert($(this).val());
});
});
Upvotes: 1
Reputation: 17314
Well I see a few possible errors:
Remove the space in the first line selector.
select#dealername
That means "the select tag with an id of dealername." Your version is "the element called dealername that is a child of a select tag".
Also, when writing inline functions, put () after the function
keyword.
Upvotes: 0
Reputation: 62392
It's because you're not selecting it correctly
var select = $('select #dealerName');
should be
var select = $('select#dealerName');
BUT... I'm assuming you want to get the value after it is selected? as it stands as soon as you open the dropdown you will get an alert.
Instead of using .click()
, use .change()
EDIT : Personally I would just attach the handler directly on the object.
$('select#dealerName').change(function() {
alert($(this).val());
}
Upvotes: 5