![](/img/trans.png)
[英]JQuery validation-input text field to be required if checkbox checked
[英]Input Field Validation If Adjoining Checkbox Is Checked
我有一个具有多个值的公共字段“服务”表格。 我创建了一个“其他”选项供选择。 我想使用“其他”选项旁边的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正常工作,如下所示:
<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>
但是,如果选中了复选框中的“其他”选项,我将无法获得验证输入字段的方法。
尝试以下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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.