Javascript 如果选中无线电,则需要输入字段
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11967519/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
make a input field required if radio is checked
提问by Morten Hagh
Can I somehow insert the required attribute into an input field only if a certain radio is checked?
只有在选中某个收音机时,我才能以某种方式将所需的属性插入到输入字段中吗?
I have an input field named "ladder-meters" that is not required to be filled per default. But if the user checks a radio button that is named "ladder" the "ladder-meters" field are required to be filled.
我有一个名为“ladder-meters”的输入字段,默认情况下不需要填写。但是,如果用户选中名为“ladder”的单选按钮,则需要填写“ladder-meter”字段。
My input looks like this:
我的输入如下所示:
<input type="text" name="ladder-meters" id="ladder-meters">
and should like this at the onchange event on the radio
并且应该在收音机的 onchange 事件中喜欢这个
<input type="text" name="ladder-meters" id="ladder-meters" required>
采纳答案by F. Orvalho
Easy to achieve with jQuery:
使用 jQuery 很容易实现:
$('#ladder').change(function () {
if($(this).is(':checked') {
$('#ladder-meters').attr('required');
} else {
$('#ladder-meters').removeAttr('required');
}
});
回答by lordyoum
Tried F. Orvalho, didn't work for me, I had to use
尝试过 F. Orvalho,对我不起作用,我不得不使用
$('#ladder').change(function () {
if(this.checked) {
$('#ladder-meters').prop('required', true);
} else {
$('#ladder-meters').prop('required', false);
}
});
It could be usefull. Thx to F. Orvalho for the structure
它可能很有用。感谢 F. Orvalho 的结构
回答by ColBeseder
document.getElementById("ladder").addEventListener('change', function(){
document.getElementById("ladder-meters").required = this.checked ;
})
Whenever the checkbox is clicked, the required attribute will be changed to match the checked attribute of the checkbox. To reverse this relationship, replace this.checked
with !this.checked
每当单击复选框时,必填属性将更改以匹配复选框的选中属性。要扭转这种关系,请替换this.checked
为!this.checked
This may need some adjustment to suit your specific project.
这可能需要进行一些调整以适合您的特定项目。
This will work with this checkbox:
这将与此复选框一起使用:
<input type='checkbox' id='ladder' name='ladder' />