如果选中此复选框,则需要输入 [英] If checkbox selected make input required

查看:75
本文介绍了如果选中此复选框,则需要输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作为Web表单的一部分,我有两个复选框(均名为 my_checkbox)和两个输入fileld(一个名为 input1,另一个名为 input2)。

As part of a web form, I have two checkboxes (both with the name "my_checkbox") and two input filelds (one with the name "input1" and the other named "input2").

<input type="checkbox" name="my_checkbox" value="some text" onclick="a function;    checkBoxValidate(0);">

<input type="checkbox" name="my_checkbox" value="some diffrent text" onclick="a diffrent function; checkBoxValidate(1);">

<input id="input1" name="input1"  />

<input id="input2" name="input2"  />

如果用户选择第一个复选框,则input1不能为空。如果用户选择第二个复选框,则input2不能为空。两个复选框必须具有相同的名称。函数checkBoxValidate确保不能同时选择两个复选框(我不喜欢单选按钮)。

If user selects the first checkbox, input1 must not be empty. If user selects the second checkbox, input2 must not be empty. The two checkboxes must have the same name. Function checkBoxValidate assures the two checkboxes cannot be selected at the same time (I don't like radio buttons).

我的JavaScript:

My javascript:

}else if (!document.myform.my_checkbox[0].checked && myform.input1.value == ''){ 
alert ('Please enter some text!',function(){$(myform.input1).focus();}); 
return false;

}else if (!document.myform.my_checkbox[1].checked && myform.input2.value == ''){ 
alert ('Please enter some text!',function(){$(myform.input2).focus();}); 
return false;

当然,没有任何效果!请帮忙? :)

Of course, nothing works! Please help? :)

推荐答案

看到您可能想简单一点,我将其编写为简单代码并使用纯JS,因为您没有标记jQuery问题。

Seeing you might want to take this simple, I write it simple and use plain JS since you did not tag the question with jQuery.

实时演示

window.onload=function() {
  var form1=document.getElementById("form1"); // assuming <form id="form1"
  form1.onsubmit=function() {
    if (this.my_checkbox[0].checked && this.input1.value=="") {
      alert("Please enter something in input 1");
      this.input1.focus();
      return false;
    }
    if (this.my_checkbox[1].checked && this.input2.value=="") {
      alert("Please enter something in input 2");
      this.input2.focus();
      return false;
    }
    return true; // allow submission
  }
  // if the checkboxes had different IDs this could have been one function
  form1.my_checkbox[0].onclick=function() {
    this.form.my_checkbox[1].checked=!this.checked;
  }
  form1.my_checkbox[1].onclick=function() {
    this.form.my_checkbox[0].checked=!this.checked;
  }
}

这篇关于如果选中此复选框,则需要输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆