如果选中相邻复选框,则输入字段验证
Posted
技术标签:
【中文标题】如果选中相邻复选框,则输入字段验证【英文标题】:Input Field Validation If Adjoining Checkbox Is Checked 【发布时间】:2014-08-14 22:40:50 【问题描述】:我有一个包含多个值的表单,用于公共字段“服务”。我创建了一个选项“其他”供选择。我想使用“其他”选项旁边的 javascript 输入字段进行验证。 代码如下
<label for="service" style="font-size:15px; vertical-align:top;">Service You Want*</label>
<input type="checkbox" name="service[]" id="Complete new set up " value="Complete new set up ">Complete new set up<br>
<input type="checkbox" name="service[]" id="Standardization" value="Standardization ">Standardization<br>
<input type="checkbox" name="service[]" id="Training" value="Training">Training <br>
<input type="checkbox" name="service[]" id="Trouble shooting " value="Trouble shooting ">Trouble shooting <br>
<input type="checkbox" name="service[]" id="Addition of new techniques" value="Addition of new techniques">Addition of new techniques<br>
<input type="checkbox" name="service[]" id="Hands on training" value="Hands on training">Hands on training<br>
<input type="checkbox" name="service[]" id="Seminars & Workshops" value="Seminars & Workshops">Seminars & Workshops<br>
<input type="checkbox" name="service[]" id="Preparations of documents" value="Preparations of documents ">Preparations of documents <br>
<input type="checkbox" name="service[]" id="Other" onclick="enable_text(this.checked)" value="other" >Other
<input type="text" name="other_text"><br>
对于“其他”选项,如果选中“其他”选项,则输入文本字段将启用。
用于启用输入字段的工作 javascript 是:
<script>
function enable_text(status)
status=!status;
document.formname.other_text.disabled = status;
</script>
javascript used to select at least one service is working,具体如下:
<script>
var chks = document.getElementsByName('service[]');
var hasChecked = false;
for (var i = 0; i < chks.length; i++)
if (chks[i].checked)
hasChecked = true;
break;
if (hasChecked == false)
alert("Please Select At Least One Service.");
return false;
</script>
但如果选中复选框中的“其他”选项,我不知道如何验证输入字段。
【问题讨论】:
【参考方案1】:尝试以下javascript:
<script>
var chks = document.getElementsByName('service[]');
var hasChecked = false;
for (var i = 0; i < chks.length; i++)
if (chks[i].checked)
hasChecked = true;
break;
if (hasChecked == false)
alert("Please Select AtLeast One Service.");
return false;
function isBlank(str)
return (!str || /^\s*$/.test(str));
if (document.getElementById("Other").checked && isBlank(document.getElementsByName('other_text').value))
alert("Please Enter Details ABout Other Services You Want......... ");
document.contactus.other_text.focus();
return false;
</script>
【讨论】:
以上是关于如果选中相邻复选框,则输入字段验证的主要内容,如果未能解决你的问题,请参考以下文章