Gus Fune
Gus Fune

Reputation: 653

jQuery function is resetting dropdown selection

I have a drop-down menu in my page, it's something like this:

   <select id="my_dropdown" name="my_dropdown">
       <option value="one">ONE</option>
       <option value="two">TWO</option>
       <option value="three">THREE</option>
   </select>
   <input type="text" size="10" id="foobar" value="0" />

And my jQuery code is:

   $('#foobar').keyup(function(){
       notOptionOne();
   }

   function notOptionOne() {
       if ( !$('#my_dropdown').val('one') ) {
           alert('Option ONE was not selected');
       }
   }

No matter what is the selection on my dropdown, when I enter any text on the input box, it will show up the alert box and will reset my dropdown selection back to one. I want to keep my selection on where I leave when I close the alert box or do anything else. What is causing this behaviour?

Upvotes: 0

Views: 198

Answers (4)

Ram
Ram

Reputation: 144659

try this:

$('#my_dropdown').change(function(){
   if ($(this).val() != 'one') {
      alert('Option ONE was not selected');
   }
})

Upvotes: 1

Daniil Ryzhkov
Daniil Ryzhkov

Reputation: 7596

$('#my_dropdown').val('one') will set #my_dropdown's value as one (even in if construction).

You should get the value of #my_dropdown element and compare it with string one:

function notOptionOne() {
    if ($('#my_dropdown').val() != "one") {
       alert('Option ONE was not selected');
    }
}

Upvotes: 1

Engineer
Engineer

Reputation: 48793

Try this:

$('#my_dropdown').val() !== 'one' 

$('#my_dropdown').val('one') is jquery wrapper, array-like object. That is why !$('#my_dropdown').val('one') is always false and you don't get an alert.

Upvotes: 1

Jerry
Jerry

Reputation: 435

   function notOptionOne() {
   if ( $('#my_dropdown').val()!='one' ) {
       alert('Option ONE was not selected');
   }
   }

The val() function in jQuery can both get a value or set a value. when you pass a parameter to it, what jQuery do is to set the value of the control. If no parameter, get value.

Upvotes: 3

Related Questions