如果单选按钮具有特定值,我试图在HTML中禁用输入字段。我已经使用了相同的Javascript函数。
CODE SNIPPET 1 :( HTML RADIO BUTTON)
<div class="element-radio">
<label class="title">Children</label>
<div class="column column2">
<label>
<input type="radio" name="children" value="Yes" onChange="findselected()"/>
<span>Yes</span>
</label>
</div>
<span class="clearfix"></span>
<div class="column column2">
<label>
<input type="radio" name="children" value="No" checked="checked" onChange="findselected()"/>
<span>No</span>
</label>
</div>
<span class="clearfix"></span>
</div>
<div class="element-number">
<label class="title">No of children</label>
<div class="item-cont">
<input class="large" type="text" min="0" max="100" name="no_children" placeholder="If YES, Number of Children?" value="<?php echo $no_children?>" />
<span class="icon-place"></span>
</div>
</div>
代码SNIPPET 2 :( JAVASCRIPT FUNCTION)
<script type="text/javascript">
function findselected() {
if (document.form.children.value == 'No') {
document.form.no_children.disabled=true;
// return false; // not sure this line is needed
} else {
document.form.no_children.disabled=false;
// return false; // not sure this line is needed
}
}
</script>
这不能按要求的方式工作。有没有更好的方法去做同样的事情?我对Javascript很新,所以我无法实现复杂的代码。
答案 0 :(得分:3)
使用以下代码更新脚本:
function findselected() {
var result = document.querySelector('input[name="children"]:checked').value;
if(result=="Yes"){
document.getElementById("inputtext").setAttribute('disabled', true);
}
else{
document.getElementById("inputtext").removeAttribute('disabled');
}
}
在输入控件中添加id
属性为id="inputtext"
。
<input id="inputtext" class="large" type="text" min="0" max="100" name="no_children" placeholder="If YES, Number of Children?" value="<?php echo $no_children?>" />