TLR
TLR

Reputation: 587

Alert on value change in select

I'm trying to alert the user when the value of a select changes to a specific one, but I have multiple select in my page (one for each user).

Here is what I tried: http://jsfiddle.net/mEFQq/

$(document).ready(function() {
    $("select").change(function(){
        if($(this).text() == "Chef")
            {
                alert();
            }
        });
});

My wish is to have an alert when the select changes to the value "Chef".

How do I do this?

Upvotes: 2

Views: 24283

Answers (3)

Pevara
Pevara

Reputation: 14310

something like this perhaps: http://jsfiddle.net/mEFQq/1/

You need to use the .val() function, not the .text() function when working with selects.

Also you need to compare with the value attribute (1 in this case) not the actual text value.

The code looks like this:

$(document).ready(function() {
    $("select").change(function(){
        if($(this).val() == "1")
            {
                alert('value 1 (wich refers to Chef) got selected');
            }
        });
});

Upvotes: 5

Adil Shaikh
Adil Shaikh

Reputation: 44740

FIDDLE

You can do something like this:

if($(this).find('option:selected').text() == "Chef")

Upvotes: 0

DarkAjax
DarkAjax

Reputation: 16223

Your problem is that using the .text() method will return all the text on your select elements, not just the "selected" one, and if you tried to use .val(), you'd the selected element's value attribute instead (if they had no set value, you could use .val()).

I suggest you change your if to: if($(this).children(':selected').text() == "Chef"), like this:

$("select").change(function(){
    if($(this).children(':selected').text() == "Chef")
        {
    alert();
        }
    });
});

Demo: http://jsfiddle.net/darkajax/YCznv/

Upvotes: 0

Related Questions