0

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.

3 Answers 3

5

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());
}
Sign up to request clarification or add additional context in comments.

2 Comments

That doesn't alert anything. How can I test to see if jquery is being called at all?
Also your function call looks funky: $(function () {
1

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

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.