Jquery 检查两个输入的相同值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8692488/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Jquery check two inputs for same value
提问by boruchsiper
I've been trying to write Jquery code to check if two inputs have the same value on form submit without luck.
我一直在尝试编写 Jquery 代码来检查两个输入在表单提交上是否具有相同的值而没有运气。
If input with id "id1" has the same value as input with id "id2" alert "some text" and return false.
如果 ID 为“id1”的输入与 ID 为“id2”的输入具有相同的值,则警告“一些文本”并返回 false。
Any help would be much appreciated.
任何帮助将非常感激。
$('#form').submit(function() {
var id1 = $(#id1).text();
var id2 = $(#id2).text();
if (id1 == id2) {
alert('Error, cant do that');
return false;
}
else
{
return true;
}
});
回答by Scott
回答by alex
It's pretty simple, just do a comparison with ==
and the input's values. Place this inside of the submit()
of your form.
这很简单,只需与==
输入的值进行比较即可。把它放在submit()
你的表格里面。
var match = $('#id1').val() == $('#id2').val();
If match
is false
, then you can show your alert()
and event.preventDefault()
.
如果match
是false
,那么您可以显示您的alert()
和event.preventDefault()
。
回答by Gajahlemu
Maybe you have miss type your code, try to replace from $(#id1)
to $('#id1')
so as from $(#id2)
to $('#id2')
也许您错过了输入代码,请尝试将 from $(#id1)
to替换$('#id1')
为 from $(#id2)
to$('#id2')
Corrected code
更正的代码
$('#form').submit(function() {
var id1 = $('#id1').text(); //if #id1 is input element change from .text() to .val()
var id2 = $('#id2').text(); //if #id2 is input element change from .text() to .val()
if (id1 == id2) {
alert('Error, cant do that');
return false;
}
else
{
return true;
}
});