sehummel
sehummel

Reputation: 5568

Get value of dropdown in jquery

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

Answers (3)

Paolo Bergantino
Paolo Bergantino

Reputation: 488374

Five things:

  1. 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.

  2. 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.

  3. click will fire as soon as someone clicks on the select as opposed to when a new option is chosen. You probably want change

  4. 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.

  5. 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

Tesserex
Tesserex

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

jondavidjohn
jondavidjohn

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

Related Questions