jQuery的隐藏选择的选项时/显示输入等于 [英] jQuery Hide / Show input when selected option is equal to
本文介绍了jQuery的隐藏选择的选项时/显示输入等于的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果所选选项等于2,我想在正文中添加以下行:
If selected option is equal to 2, I want to add the following line to the body:
<input id="fnivel2" pk="1"/>
我使用隐藏类做到了.它可以工作,但是我不确定这是否是正确的解决方案:
I did it using a hide class. It works but I'm not sure if it is a correct solution:
<script>
$(document).ready(function (){
$("#fnivel").change(function(){
var selected_option = $('#fnivel').val();
if(selected_option == '2'){
$("#fnivel2").removeClass("hide");
$("#fnivel2").attr('pk','1');
}
if(selected_option != '2'){
$("#fnivel2").addClass("hide");
$("#fnivel2").removeAttr('pk');
}
})
});
</script>
<select id="fnivel">
<option value="1">one</option>
<option value="2">two</option>
<option value="3">three</option>
</select>
<input id="fnivel2" class="hide" />
推荐答案
这里是一个选项,首先是HTML:
Here is an option, first the HTML:
<select id="fnivel">
<option value="1">one</option>
<option value="2">two</option>
<option value="3">three</option>
</select>
<input id="fnivel2" hidden="hidden" />
JavaScript:
The JavaScript:
$("#fnivel").change(function () {
var selected_option = $('#fnivel').val();
if (selected_option === '2') {
$('#fnivel2').attr('pk','1').show();
}
if (selected_option != '2') {
$("#fnivel2").removeAttr('pk').hide();
}
})
这是一个 JsFiddle 的示例.
另一种方法,具体取决于您的要求,例如以编程方式创建输入控件.
Another approach, depending on your requirements is to create the input control programmatically, e.g.
$('#fnivel2').append('<input id="fnivel2" pk="1"/>').show();
这篇关于jQuery的隐藏选择的选项时/显示输入等于的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文