Kal
Kal

Reputation: 988

jQuery select value switches to default on change

my code is here http://jsfiddle.net/2BcS3/

$("#b").click(function(){
 //should output: [user selection] - []
 alert("[" + $("#s").val() + "] - [" + $("#i").val() + "]"); 


 $("#i").val('nice');    
 //should output: [user selection] - [nice]
 alert("[" + $("#s").val() + "] - [" + $("#i").val() + "]"); 

 //should output: [nice] - [nice]
 $("#s").val($("#i").val());
 alert("[" + $("#s").val() + "] - [" + $("#i").val() + "]"); 
});

and the html

<select id='s'>
 <option value='0'>select</option>
 <option value='1'>ok</option>
 <option value='2'>no</option>
</select>
<input id='i' type='hidden' />
<button type='button' id='b'>go</button>

you will notice the issue right away. I am trying to change the value of the select to what has been input in a hidden field dynamically. For some reason the select does not take in the new value and switches automatically to the first value of the select list !!!

Upvotes: 0

Views: 138

Answers (3)

StackSlave
StackSlave

Reputation: 10617

Try option:selected, like:

$("#b").click(function(){
  //should output: [user selection] - []
  alert("[" + $("#s").val() + "] - [" + $("#i").val() + "]"); 


  $("#i").val('nice');    
  //should output: [user selection] - [nice]
  alert("[" + $("#s").val() + "] - [" + $("#i").val() + "]"); 

  //should output: [nice] - [nice]
  $("#s option:selected").attr('value', $("#i").val());
  alert("[" + $("#s").val() + "] - [" + $("#i").val() + "]"); 
});

I updated your fiddle at http://jsfiddle.net/2BcS3/3/ .

Upvotes: 0

Lochemage
Lochemage

Reputation: 3974

You need to use the currently selected option, not just the value of the 'select' element.

$("#s :selected").val();

Your script should look more like this:

$("#b").click(function(){
    //should output: [user selection] - []
    alert("[" + $("#s :selected").val() + "] - [" + $("#i").val() + "]"); 


    $("#i").val('nice');
    //should output: [user selection] - [nice]
    alert("[" + $("#s :selected").val() + "] - [" + $("#i").val() + "]"); 

    //should output: [nice] - [nice]
    $("#s :selected").val($("#i").val());
    alert("[" + $("#s :selected").val() + "] - [" + $("#i").val() + "]"); 
});

Upvotes: 0

DarkAjax
DarkAjax

Reputation: 16223

The problem is that your trying to force the select to have a value that doesn't exist within it's options, if you add <option value='nice'>nice!</option> to the select, your code will work...

JSFiddle Demo

Upvotes: 1

Related Questions