2013-04-24 116 views
0

我必須創建一個輸入文本框和選擇框。在select中,選項將包含一些userId值是用戶名。用戶可以使用文本框和選擇框來輸入數據。如果他/她選擇了任何用戶名,那麼userId應該在文本框中更新。反之亦然,如果用戶在文本框中輸入userId userId應在文本框中更新。jquery選擇選項應根據選項編號選擇

功能的第一部分工作正常。

我沒有得到任何jQuery解決方案,如何使特定的選項ID選擇。

第二部分

這些動態地選擇和輸入框創建。這些將會增加。我需要爲每個人做。我如何爲使用jQuery的人做同樣的功能。

<input type="text" id="demoInput" /> 

    <select id="demoSelect" > 
    <option id="0">User Name A</option> 
    <option id="1">User Name B</option> 
    <option id="3">User Name C</option> 
    <option id="4">User Name D</option> 
    <option id="5">User Name E</option> 
    <option id="6">User Name F</option> 
    </select> 

    $('#demoSelect').change(function(){ 
     //alert('event fired'); 
     var id = $(this).children(":selected").attr("id"); 
     //alert('id is ' +id);  
     $('#demoInput').val(id); 
    }); 

$('#demoInput').change(function(){ 
     alert('event fired'); 
     $('#demoSelect').children(":selected").removeAttr("selected"); 


     alert('id is ' +id);  
     $('#demoInput').val(id); 
    }); 

我創建了this JS小提琴。

回答

0

我想這不起作用,因爲當#demoInput的值發生變化時,實際上並沒有更新#demoSelect的值。

$('#demoInput').change(function(){ 
    var value = $(this).val(); 
    $('#demoSelect option:selected').removeAttr('selected'); 
    $('#demoSelect option#' + value).attr('selected', 'selected'); 
}); 
1

你有幾件事情錯

  1. option應該有一個屬性valueid
  2. 當得到一個select的設定值,使用jQuery使用$('#demoSelect').val()
  3. 設置當選擇值爲select,使用jQuery使用$('#demoSelect').val(newValue)

所以,你的選擇框變爲:

<select id="demoSelect" > 
<option value="1">Option 1</option> 
<option value="2">Option 2</option> 
<option value="3">Option 3</option> 
<option value="4">Option 4</option> 
<option value="5">Option 5</option> 
<option value="6">Option 6</option> 
</select> 

而當你改變文本框成爲其觸發代碼:

$('#demoInput').change(function(){ 
    alert('event fired'); 
    $('#demoSelect').children(":selected").removeAttr("selected"); 

    var id= $(this).val();      
    alert('id is ' +id);  
    $('#demoSelect').val(id); 
}); 

工作您的jsfiddle的分支:http://jsfiddle.net/CGQ7N/

1

當你的id沒有初始化,並且你在做錯誤的綁定。更新你的change事件爲keyup事件,因爲每次點擊外需要點擊事件:)

你可以使用$('#demoInput').get(0)方法作爲索引從0開始我們需要減去-1來得到它嗎?

特意用指定索引,.get(index)將檢索一個元素:

$('#demoInput').keyup(function(){ 
     alert('event fired'); 
     $('#demoSelect').children(":selected").removeAttr("selected"); 

     var id= $("#demoInput").val() 
     alert('id is ' +id);  
     $('#demoSelect').get(0).selectedIndex = id-1; 
    }); 

Demo

0

我是這樣做的:

$('#demoInput').change(function(){ 
     var $val = $('#demoInput').val(); //get the value of the input 
     $('#demoSelect').children(":selected").removeAttr("selected"); //unselect any selected option 
     $('#demoSelect').find('#'+$val).attr('selected',true); //find the option with id="<input value>" and select it 
    }); 

的jsfiddle:http://jsfiddle.net/7GUaq/22/