2012-04-19 99 views
0

我有一個<select></select>現在列表中包含像a, b, and c現在我想一些選項,當用戶在textboxa,點擊按鈕a應在選擇列表中選擇,從今以後,任何人都可以幫我在JQuery中做到這一點。設置列表中的選項中選擇使用JQuery

回答

2

假設這是您的select

<select> 
    <option id="a" value="a"/> 
    <option id="b" value="b"/> 
    <option id="c" value="c"/> 
    <option id="d" value="d"/> 
</select> 

這就是你input

<input type="text" id="textbox" /> <input type="button" id="button"/> 

這是你的script

<script> 
    $('#button').click(new function(){ 
     var option = $("#textbox").val(); 
     $('select #'+option).attr("selected='true'"); 
    }); 
</script> 

這項工作?

2

對於像下面的標記,

<select id="selectOpt"> 
    <option value="a">a</option> 
    <option value="b">b</option> 
    <option value="c">c</option> 
</select> 

<input type="textbox" id="txtbox1" /> 

<button id="sch">Select</button> 

下面的腳本應該做的伎倆,

$('#sch').on('click', function() {  //<-Bind click handler for button using .on 
    var txtVal = $('#txtbox1').val(); //<-Get the value entered in the textbox 

    if ($('#selectOpt option[value=' + txtVal + ']').length > 0) { 
     //^-- Above line checks if the entered value exist in the options list 

     $('#selectOpt').val(txtVal); //<-Set the value of the select with the entered value 
    } 
}); 

DEMO

+0

您應該進行檢查以確保選項存在。雖然它可能沒有區別。 – 2012-04-19 20:26:13

+0

@DavidThomas是的,問題是不完整的..所以我扔了一個粗糙的版本。 – 2012-04-19 20:26:47

+0

我知道;但只要你試圖回答... = b – 2012-04-19 20:28:34

2

的Javascript:

$(function(){ 
    $("#someButton").click(function(){ 
    $("#someSelect").val($("#someInput").val()); 
    }); 
}); 

HTML:

<select id="someSelect"> 
    <option>a</option> 
    <option>b</option> 
    <option>c</option> 
</select> 
<input id="someInput" type="text" /> 
<button id="someButton">Go</button> 

看到這裏工作的例子:http://jsbin.com/ipevaz/3/edit

+0

您將使用該代碼單擊任意*按鈕後,將* all *選項的值設置爲* all * input元素的第一個值。 – 2012-04-19 20:27:16

+0

我知道這一點。如果他不明白,那麼他可能根本不應該使用jquery。 – 2012-04-19 20:28:33

+0

看問題,你認爲他/她理解jQuery嗎? – 2012-04-19 20:29:07

0
<select> 
    <option value="a">a</option> 
    <option value="b">d</option> 
    <option value="c">c</option> 
</select> 

<input type="text" id="letext" maxlength="1"/> 
<input type="button" id="select" value="Select" /> 
​ 


$('#select').click(function(){ 

    $('select option[value=' + $('#letext').val() +']').prop('selected','true') 
    });​ 

http://jsfiddle.net/chepe263/UNmT8/

按鈕功能是找到等於輸入

0

您可以使用下面的HTML做到這一點的價值選擇。

<input type="text" id="input" /> 
<input type="button" id="btn" value="Move to Select" /> 

<select> 
    <option value="a">a</option>  
    <option value="b">b</option>  
    <option value="c">c</option> 
</select>​ 

以及這個jQuery代碼片段。

<script type="text/javascript"> 
    $(function() { 
     $('#btn').click(function() { 
      $('select option[value="' + $('#input').val() + '"]').prop('selected', true); 
     }); 
    });​ 
</script> 

查看this Fiddle進行工作演示。希望有所幫助! :)