0

I have two input field. one with name and other is verify name. I want to add some validation into it. If my first input contains 'robert' then user only can type "robert" in next field. But it is not giving me the desire result

<head>
<script type="text/javascript">
$(function(){
var jn= [];
$('#first').keypress(function(e){
var d= e.charCode || e.keyCode;
jn.push(d)})

var jm=[];      
$('#second').keypress(function(e){
var f= e.charCode || e.keyCode;
jm.push(f)
for(i=0;i<jn.length;i++){
for(z=0;z<jm.length;z++)
{
if(jn[i]==jm[z]){
alert('hiii')}}}})
})
</script>
</head>
<body>
name
<input type="text" id="first" />
verify name
<input type="text" id="second" />
    </body>
2
  • 2
    You're missing a bunch of semicolons, you either put them all or none, but mixing is not good. Commented Nov 14, 2012 at 7:05
  • I wasn't sure if you needed to prevent non matching characters from being entered altogether, or to validate that the were the same after the user is done editing the second field. If it's the former, my solution is okay. If it's the latter, Abdul's answer is sufficient. Commented Nov 14, 2012 at 7:26

3 Answers 3

1

I believe you're over thinking it. Your solution also doesn't lend itself to editing (due to having to track the array of keycodes). Try something like this

http://jsfiddle.net/qccQZ/3/

$("#field2").keypress(function(e){
    var f1 = $("#field1").val();
    var len = $(this).val().length;
    var str = String.fromCharCode(e.charCode)
    if(f1.charAt(len) != str) return false;
});​
Sign up to request clarification or add additional context in comments.

Comments

1
$('#second').blur(function(){
if($('#first').val() != '' && ($('#first').val() == $('#second').val()))
alert('valid');
else
alert('invalid');
});

Test: http://jsfiddle.net/Dzb8c/

Comments

0

I think you should use this for loop

for(i=0;i<jm.length;i++){
     if(jn[i]!=jm[i])
       {
         alert('hiii');
       }
  }

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.