Adi
Adi

Reputation: 123

Comparing variables in jQuery

I'm using simple jQuery to compare two variables, but every time it is yielding false result. Here is the code piece:

 var fromIM = $("#passwordFroma").val();
 loadContent(passwordValentered);
 var encrypt = document.getElementById("prtCnt").value;
 alert("ajax call " + encrypt);
 alert(encrypt == fromIM);

In the above code piece,

passwordFroma is a hidden text field.
passwordValentered is a text box to get user input.
prtCnt is a hidden field.

Also, loadContent(passwordValentered) function is an ajax call which sets the value for hidden field prtCnt. This is confirmed from the first alert. But, when I compare the values in second alert, I always get the result as false.
Please let me know where am I going wrong! I'm using jQuery 1.9.

Upvotes: 1

Views: 2187

Answers (1)

Ruan Mendes
Ruan Mendes

Reputation: 92274

Your generated field with id prtCnt is generated asynchronously (AJAX), therefore it's not accessible immediately after the call to loadContent(passwordValentered);

var fromIM = $("#passwordFroma").val();
// Sends AJAX
loadContent(passwordValentered);
// AJAX is not finished here
var encrypt = document.getElementById("prtCnt").value;
alert("ajax call " + encrypt);
alert(encrypt == fromIM);

You have to pass a callback to loadContent

var fromIM = $("#passwordFroma").val();
loadContent(passwordValentered, function(){
   var encrypt = document.getElementById("prtCnt").value;
   alert("ajax call " + encrypt);
   alert(encrypt == fromIM);
});

And modify your loadContent so that it calls the given callback from the success handler of $.ajax

Upvotes: 3

Related Questions