选择特定选项时,在选择下拉菜单中添加输入框

Rya*_*ons 3 html javascript jquery select input

我需要在选择时将输入添加到选择选项。只要用户选择“其他”,就会有一个输入框供用户输入数据。

的HTML:

<select>
  <option>Choose Your Name</option>
  <option>Frank</option>
  <option>George</option>
  <option>Other</option>
</select>

<!-- when other is selected add input
<label>Enter your Name
<input></input>
</label> -->
Run Code Online (Sandbox Code Playgroud)

我的jsfiddle:http : //jsfiddle.net/rynslmns/CxhGG/1/

Ish*_*ain 7

您可以使用jquery .change()绑定元素的change事件。

试试这个:

的HTML

<select>
  <option>Choose Your Name</option>
  <option>Frank</option>
  <option>George</option>
  <option>Other</option>
</select>
<label style="display:none;">Enter your Name
<input></input>
</label>
Run Code Online (Sandbox Code Playgroud)

jQuery的

$('select').change(function(){
     if($('select option:selected').text() == "Other"){
        $('label').show();
     }
     else{
        $('label').hide();
     }
 });
Run Code Online (Sandbox Code Playgroud)

试试小提琴

更新:

您还可以动态添加输入框-

的HTML

<select>
  <option>Choose Your Name</option>
  <option>Frank</option>
  <option>George</option>
  <option>Other</option>
</select>
Run Code Online (Sandbox Code Playgroud)

jQuery的

$('select').change(function(){
   if($('select option:selected').text() == "Other"){
        $('html select').after("<label>Enter your Name<input></input></label>");
   }
   else{
        $('label').remove();
   }
});
Run Code Online (Sandbox Code Playgroud)

试试小提琴