检查两个表单字段
喜 我想两个检查两个字段 如果两个字段的值相同,则其显示一个消息二我,我有一个代码,但检查两个表单字段
它不工作,你能告诉我什么拨错这个代码
<script type="text/javascript">
function checkForm(form1){
if(form1.field1.value == form1.field2.value){
alert(" values are identical");
form1.field1.focus();
return true;
}else{
return false;
}
}
</script>
<form name="form1" method="POST" action="" >
<input type="text" name="field1">
<input type="text" name="field2">
<input type="submit" onClick="return checkform1(this);" >
</form>
更改,如果条件这样
if(document.form1.field1.value==document.form1.field2.value)
我改变了它,但没有消息将显示 – amit 2011-02-28 06:22:38
当你在你的按钮 – 2011-02-28 06:28:32
的onclick事件中调用它时,并且你在提交按钮的onclick事件中调用函数checkform1时,将它从函数中删除。但是你已经将函数定义为checkForm。在打电话时使表格名称类似。这也是你的拼写错误 – 2011-02-28 06:31:10
你打电话checkform()
,但不会在任何位置定义。另外,checkform1(this)
使用该按钮作为元素form1
,它将所有东西都拧紧。使用this.parentNode
,它将形式作为参数传递。
这里的一些工作代码:
<script>
function checkForm(form1) {
if (form1.field1.value == form1.field2.value) {
alert(" values are identical");
form1.field1.focus();
return true;
} else {
return false;
}
}
</script>
<form name="form1" method="POST" action="" >
<input type="text" name="field1">
<input type="text" name="field2">
<input type="submit" onClick="return checkForm(this.parentNode);" >
</form>
您需要在您的形式选择前加document.
。而且您的方法名称与您通过点击事件调用的方法不符。
,我已经修复它,这里包括一个例子:http://jsfiddle.net/jomanlk/Fu2wJ/1/
function checkForm(form1) {
if (document.form1.field1.value == document.form1.field2.value) {
alert(" values are identical");
document.form1.field1.focus();
return false;
}
else {
return true;
}
}
<form name="form1" method="POST" action="" >
<input type="text" name="field1">
<input type="text" name="field2">
<input type="submit" onClick="return checkForm();" >
</form>
除了事实checkForm1
功能不存在,主要的问题在于
<input type="submit" onClick="return checkform1(this);" >
这里this
是指input
而不是form
。
为了使你的代码的工作改变函数名checkForm
和
<input type="submit" onClick="return checkform1(this.form);" >
对于初学者来说,你打电话'checkform1'和你的功能被命名为'checkForm'。 – zdyn 2011-02-28 06:22:05