Anna
Anna

Reputation: 203

Compare two Strings in javascript, obtained from a form element using jQuery

I want to compare two strings in jQuery, which is very easy, but I get all the time 'yes' in the console, doesn't matter if the passwords are the same or different, any ideas? Thanks!

ns.resetPassword = function(){
    var password1 = $.trim($('#password1').val());
    console.log(password1);
    var password2 = $.trim($('#password2').val());
    console.log(password2);

    if(password1==password2){
      console.log('yes!');
    }else{
      console.log('different!');
    }
  }

HTML:

<input class="form-text" id="password1" name="password.password1" type="password" maxlength="128" size="60" placeholder="@Messages("securesocial.passwordChange.newPassword1")">

<input class="form-text" id="password2" name="password.password2" type="password" maxlength="128" size="60" placeholder="@Messages("securesocial.passwordChange.newPassword2")">

I changed the id from password.password1 to password1 as some of you suggested

Upvotes: 1

Views: 10314

Answers (2)

Satpal
Satpal

Reputation: 133403

Use === instead of ==

You also need to use escape . in selector

 $('#password\\.password1').val()

From Reference

To use any of the meta-characters ( such as !"#$%&'()*+,./:;<=>?@[]^`{|}~ ) as a literal part of a name, it must be escaped with with two backslashes: \\.

See DEMO

Note: In demo there are 2 function one with escape . and one without for comparison.

Upvotes: 4

Joy R&#234;
Joy R&#234;

Reputation: 159

Your selectors are wrong. You can use either:

$('#password1').val()

or

$('input[name="password.password1"]').val()

to get the value in your first password input box

Upvotes: 0

Related Questions