javascript 如何使用jquery比较两个文本输入类型框值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10979977/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 11:41:59  来源:igfitidea点击:

how to compare two text input type box values using jquery

javascriptjqueryasp.net

提问by user1196392

I have a two textboxes t1and t2. I would like to figure out how in jquery if the values in t1and t2are same I can display an alert message. If user does not change the values I want to prevent the form from being submitted.

我有两个文本框t1t2. 我想弄清楚如何在 jquery 中,如果t1t2中的值相同,我可以显示警报消息。如果用户不更改值,我想阻止提交表单。

回答by Manse

Try something like this

尝试这样的事情

$('form').submit(function(evt) {
   if ($('#textbox1').val() === $('#textbox2').val()) {
     alert('values match');
     evt.preventDefault();
   }
}

uses the .submit()method to bind to the submitevent for the form, then compares the 2 values from the textboxes - if they are the same it displays an alert then prevents the default action (form submission) using event.preventDefault()

使用.submit()方法绑定到submit表单的事件,然后比较文本框中的 2 个值 - 如果它们相同,则显示警报,然后使用event.preventDefault()阻止默认操作(表单提交

Working example here

这里的工作示例

回答by Anjan Kant

$("form").submit(function() {
  var _txt1 = $('#txt1').val();
  var _txt2 = $('#txt2').val();
  
  if (_txt1 == _txt2)
  {
     alert('Matching!');
     return true;
  }
  else
  {
    alert('Not matching!');
    return false;
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="#" method="post" name="form_name" id="form_id">
  <input type="text" id="txt1" name="txt1" />
  <input type="text" id="txt2" name="txt2"/>
  <input type="submit" value="Submit">
</form>

example link

示例链接

回答by Baruch

jQuery

jQuery

$(document).ready(function() {
    var _t1 = $("#t1");
    var _t2 = $("#t2");
    $(_t2).focusout(function() {
    if(_t1.val() === _t2.val()){
        return alert('Match');
    }
    return alert('No match');
  });
});

HTML

HTML

<input id="t1">
<input id="t2">

Fiddlehttps://jsfiddle.net/ptda108k/1

小提琴https://jsfiddle.net/ptda108k/1

回答by Rahul

Here is the code

这是代码

if(!$("#t1").val() && !$("#t2").val() && $("#t1").val() === $("#t2").val()){
   alert("Both values are same");
}else{
   return false;
}

I am doing strict type check for input values by ===.

我正在通过 === 对输入值进行严格的类型检查。

Hope this will help your requirement.

希望这将有助于您的要求。

回答by Mehran Ayub

<script>
function myfunction(){
var val1=document.getElementById('pwd').value;
var val2=document.getElementById('cpwd').value;
if(val1!=val2){
document.getElementById('match').innerHTML="Your password is unmatch";
return false;
}
return true;
}
</script>