我有一个带有选择菜单的 html 表单。菜单上的最后一个选项是“其他”。我想做的是,如果用户选择“其他”,则选择菜单会变成一个文本字段。我知道这可以通过 jQuery 的显示/隐藏功能来完成,但我尽量保持简单。我觉得这不太可能,但是是否有 JavaScript 命令(无论是否为 jQuery)将选择元素转换为输入元素?
最佳答案
这可以工作 ( demo )
<select id='choices' name='Choice'>
<option>Ford</option>
<option>Toyota</option>
<option>Honda</option>
<option>Other</option>
</select>
使用这个 JavaScript
$('#choices').on('change', function() {
var choice = $(this);
if(choice.val()=== 'Other') {
choice.replaceWith('<input name="Choice"/>')
}
});
或者更强大的解决方案 ( demo )
<div class='ChoiceWithOther'>
<select name='Choice'>
<option>Ford</option>
<option>Toyota</option>
<option>Honda</option>
<option>Other</option>
</select>
<input name='Choice' disabled='disabled'/><a href='#' class='UndoChoice'>×</a>
</div>
使用这个 JavaScript:
var select = $('select[name=Choice]'),
input = $('input[name=Choice]'),
undo = $('.UndoChoice');
select.on('change', function() {
if(select.val()=== 'Other') {
select.prop('disabled', true); //Disbaled inptus won't be sent on FORM submits
select.hide(); //Don't confuse user
input.prop('disabled', false);
input.show();
undo.show();
}
});
undo.on('click', function() {
select.prop('disabled', false); //Disabled inputs won't be sent on FORM submits
select.show(); //Don't confuse user
select.val($('option:first', select).val()); //reset to first value
input.prop('disabled', true);
input.hide();
undo.hide();
});
input.hide();
undo.hide();
关于javascript - 使用 JavaScript 改变 HTML 元素的性质,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21820170/