在复选框选择后验证输入类型文本

Validating input type text after Check Box Selections

本文关键字:输入 类型 文本 验证 复选框 选择      更新时间:2023-09-26

我一直在通过10个简单的步骤从javascript学习js。在任务 104 上,有在复选框选择后验证输入类型文本的任务。但是,我对选中复选框后如何抓取文本字段感到困惑。检查复选框是否选中后,我尝试将语法formName.TextareafieldName的文本字段。

然而在书中,遵循的语法是form.formName.TextareafieldName。在浏览器中输出时,它显示仅选中复选框,但无法抓取显示ERR_FILE_NOT_FOUND的文本。我的代码如下。

<form name="myForm" action="js_form_validation_with_inputcheckbox.html"
 onSubmit="return checkForm(this);">
    <input type="checkbox" name="myCheck" value="Checked"> Check Here<br>
    If checked, enter your name:
    <input type="text" name="myText"><br>
    <input type="submit">
</form>

还有这里的脚本:

<script>
function checkList(check) {
  if (check.checked) {
    if (myForm.myText.value.length == 0) {
      window.alert("You have checked the check box;you must provide your name.");
      return false;
    }
  }
  return true;
}
function checkForm(formObj) {
  return checkList(formObj.myField.value);
}
</script>

如果有人能消除我的困惑,我将不胜感激。

checkForm 传递formObj.myField.value,但没有名为 myField 的控件。也许你的意思是我的支票

此外,checkList 函数似乎需要一个控件,而不是一个值,因此传递控件。

尝试:

function checkForm(formObj) {
  // Pass the checkbox control using its name
  return checkList(formObj.myCheck); 
}

关于:

> i tried to grab the textfield with syntax as formName.TextareafieldName
文档

具有一个表单集合,该集合是文档中的所有表单。成员可以按索引或其名称或 ID 引用。在某些浏览器中,ID 将成为引用表单的全局变量,但使用该功能被认为是一个坏主意。

您可以使用以下命令引用表单:

document.forms.myForm

document.forms[0]

假设它是文档中的第一个或唯一的表单。同样,控件可以作为窗体的命名成员进行访问,因此:

var form = document.forms[0];
var myCheck = form.myCheck;
窗体

还具有一个元素集合,该集合是窗体中(或属于窗体)的所有控件,因此您还可以执行以下操作:

var myCheck = form.elements.myCheck;

var myCheck = form.elements[0];

如果 myCheck 是窗体中的第一个控件。

您可以使用此表单作为示例...

<form>
 First name:<br>
 <input name="firstname" id="firstname" type="text">
 <br>
  Last name:<br>
  <input name="lastname" type="text">
  </form>
  <br>
  <p>
  <input onchange="checkList(this);return false;" id="change"    type="checkbox">
  <span id="sp-change"></span></p>

这是脚本代码...

function checkList(ch) {
if (ch.checked) {
 var textBox = document.getElementById("firstname");
 var textLength = textBox.value.length;
 if (textLength == 0) {
  window.alert("You have checked the check box;you must provide your name.");
  return false;
  } else {
   window.alert("Success");
  return true;
 }
 }
 return false;
 }

我认为这对你有很大帮助。