[英]Add a text field to html dropdown
我有一个html下拉字段,其中应该在底部添加一个文本字段命名other:text
字段。此字段中键入的文本应该是other:text
下拉html是:
<select name="drop">
<option selected="selected">Please select ...</option>
<option value="car">car</option>
<option value="bike">bike</option>
<option value="Other">Other</option>
</select>
其他应该是文本字段。为了理解我保留其他作为选项,但我希望它是一个输入文本字段,其中值由用户给出。
提前致谢
您可以为其他文本默认添加隐藏的输入字段:
<input type='text' id='other' name='other' style="display:none"/>
并在你的js中捕获select的变化,然后检查所选的选项值是否等于Other
并显示该字段或隐藏它:
$('select').on('change', function(){
if($(this).val()=='Other'){
$('#other').show().focus();
}else{
$('#other').val('').hide();
}
})
希望这可以帮助。
$('select').on('change', function(){ if($(this).val()=='Other'){ $('#other').show().focus(); }else{ $('#other').val('').hide(); } })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select name="drop"> <option selected="selected">Please select ...</option> <option value="car">car</option> <option value="bike">bike</option> <option value="Other">Other</option> </select> <input type='text' id='other' name='other' style="display:none" value='other:'/>
<script type="text/javascript">
function showfield(name){
if(name=='Other')document.getElementById('div1').innerHTML='Other: <input type="text" name="other" />';
else document.getElementById('div1').innerHTML='';
}
</script>
<select name="drop" id="drop" onchange="showfield(this.options[this.selectedIndex].value)">
<option selected="selected">Please select ...</option>
<option value="car">car</option>
<option value="bike">bike</option>
<option value="Other">Other</option>
</select>
<div id="div1"></div>
您可以采用另一种方式,并通过文本字段访问所有选项 - 但在用户键入时提供自动完成选项。 这可以通过jQuery自动完成插件等或新的html5 datalist来完成。 这将一组预定的选项绑定到文本字段 - 允许用户在输入值与值匹配时从中进行选择,但如果没有匹配则允许输入替代文本。 请注意,Safari(以及可能的其他浏览器)尚不支持此功能。 但是当它受到支持时它非常酷。
<input id="transportOptions" list="transport">
<datalist id="transport">
<option value="Car">
<option value="Bike">
<option value="Scooter">
<option value="Taxi">
<option value="Bus">
</datalist>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.