2011-01-31 21 views
2

私はリストを取得しようとしています。jQuery:クリックした要素を入力ボックスに入れるにはどうすればよいですか?

私は、リストを保存する空の入力ボックスを持っている:メアリー、ケイト、Brockの

は今、私はそれで、これらの3つの名前を持つ選択リストを持っています。選択リストからクリックした名前を入力ボックスにどのように転送することができるかを知りたい。 2番目の名前をクリックすると、前の名前とカンマを区切ります。

あなたのお手伝いをお待ちしております。 (

+0

この質問は以前に聞かれましたが、見つかりませんでした。選択ボックスは複数選択ボックスですか?つまり、現在選択されているテキストフィールドをテキストフィールドに表示するか、選択した順序に基づいてテキストフィールドに名前を追加しますか? –

答えて

0

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

<select name="names" id="names"> 
    <option value="Mary">Mary</option> 
    <option value="Kate">Kate</option> 
    <option value="Brock">Brock</option> 
</select> 

<script> 
$(document).ready(function() { 
    $("#names").change(function() { 
     name = $(this).val(); 
     current = $("#name").val(); 
     if (!$("#name").val()) { 
      $("#name").val(name); 
     } else { 
      if (current.indexOf(name) == -1) { 
       $("#name").val(current + ', ' + name); 
      } 
     } 
    }); 
}); 
</script> 

は、リストの最後に新しい名前を追加しますが複数の名前であり、重複が今許可されているときのみ、カンマを追加します。

0

入力要素の値を$('#the_id').val();で得ることができ、同じ方法で入力要素の値を操作することができます:$('#the_id').val('new value');。それを結合します.clickハンドラで、あなたはすべて設定する必要があります。

$('#selector').click(function(){ 
    var $names = $('#names') 
    $names.val($names.val() + ', ' + $(this).val()); 
}); 
0

てみ使用changeイベント:

$('#listbox').change(function(){ 
    var selectedName = $('#listbox option[value='+$(this).val()+']').text(); 
    $('#input-for-insert').append(selectedName); 
}); 

私はあなたがあなた自身コンマ分離させると思います)

どのように
0
<input type="text" id="name" name="name" /> 

<select name="names" id="names"> 
    <option value="Mary">Mary</option> 
    <option value="Kate">Kate</option> 
    <option value="Brock">Brock</option> 
</select> 

<script> 
    $(document).ready(function() 
    { 
     // When the names selection changes 
     $("#names").change(function() 
     { 
      // Get the new name from this selection list 
      newName = $(this).val(); 

      // Get any names currently in the input box 
      currentName = $("#name").val(); 

      // Change the value of the name box by adding the newName followed by a comma 
      // followed by the current names 
      $("#name").val(newName + ", " + currentName); 
     }); 
    } 
</script> 
関連する問題