2013-07-17 19 views
0

我的代碼是在這裏http://jsfiddle.net/2BcS3/jQuery的選擇值開關上更改默認

$("#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() + "]"); 
}); 

和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> 

,你會發現這個問題的時候了。我正在嘗試將選擇的值更改爲動態輸入到隱藏字段中的值。出於某種原因,select不會獲取新值並自動切換到選擇列表的第一個值!

+0

'我'沒有價值,你怎麼設'S'? – DevlshOne

+0

s是通過選擇並在您點擊按鈕後進行更改來設置的,當您單擊該按鈕時我將被設置。檢查jsfiddle – Kal

+0

但'i'是一個字符串和'S'有可選值0,1,2 – DevlshOne

回答

0

您需要使用當前選定的選項,而不僅僅是'select'元素的值。

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

你的腳本應該看起來更像是這樣的:

$("#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() + "]"); 
}); 
+0

就是這樣。非常感謝你在過去的5個小時裏一直在推動我堅果 – Kal

+0

'$('#s option:selected')。val();'是建議的格式 – DevlshOne

1

的問題是,你試圖迫使選擇有不中它存在的價值的選項中,如果添加<option value='nice'>nice!</option>到選擇,您的代碼將工作...

JSFiddle Demo

+0

這就是要點。我試圖強制選擇一個值。該值不在列表中,而是來自不同的輸入。通過使用@Lochemage建議您將所選選項的值附加/更改爲輸入字段中的新值 – Kal

0

嘗試option:selected,如:

$("#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() + "]"); 
}); 

我更新了你的小提琴http://jsfiddle.net/2BcS3/3/

+0

謝謝。這是問題,它是固定的:) – Kal