繁体   English   中英

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

[英]Add input-box when selecting a specific option into select drop down

我需要在选择时将输入添加到选择选项。 每当用户选择“其他”时,输入框就在那里供用户输入数据。

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

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

您可以使用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>

jQuery的

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

尝试小提琴

更新:

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

HTML

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

jQuery的

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

尝试小提琴

在这里看到它。

HTML:

<select id="choose">
    <option>Choose Your Name</option>
    <option>Frank</option>
    <option>George</option>
    <option value="other">Other</option>
</select>
<label id="otherName">Enter your Name
    <input type="text" name="othername" />
</label>

jQuery的:

$(document).ready(function() {
    $("#choose").on("change", function() {
        if ($(this).val() === "other") {
            $("#otherName").show();
        }
        else {
            $("#otherName").hide();
        }
    });
});

请注意“其他”选项上的value="other"属性。 这就是脚本如何确定是否选择了“其他”选项。

希望这可以帮助!

这是一个纯javascript版本,不需要jQuery:

<script>
// Put this script in header or above select element
    function check(elem) {
        // use one of possible conditions
        // if (elem.value == 'Other')
        if (elem.selectedIndex == 3) {
            document.getElementById("other-div").style.display = 'block';
        } else {
            document.getElementById("other-div").style.display = 'none';
        }
    }
</script>

<select id="mySelect" onChange="check(this);">
        <option>Choose Your Name</option>
        <option>Frank</option>
        <option>George</option>
        <option>Other</option>
</select>
<div id="other-div" style="display:none;">
        <label>Enter your Name
        <input id="other-input"></input>
        </label>
</div>

jsFidle

如前所述,添加onChange事件,将其链接到函数并处理应显示的内容等。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM