Gyan Parkash Gyan Parkash - 1 month ago 5
Javascript Question

JavaScript function sending string but receiving Boolean value

I am facing the unexpected behavior of javascript function. Im an passing the ID of a field as string to function but it is receiving as bool value. Please help the code is below.

Function



function page_smooth_scroll(target_id) {
if (target_id =! null) {
$j('html, body').animate({
scrollTop: $j("#" + target_id).offset().top - 120
}, 500);
}
}





calling function



function validatePassword(){
var validPassword = false;
var pwd = $j("#Password").val().trim();
var cfmPwd = $j("#ConfirmPassword").val().trim();
if((pwd == "") || (cfmPwd == "")){
$j("#ConfirmPassword").addClass("invalidPwd").nextAll("ul.err-msg").html("<li>Please enter Password</li>");
//here id is passed as string
page_smooth_scroll("ConfirmPassword");
validPassword = false;
}
else{
$j("#ConfirmPassword").removeClass("invalidPwd").nextAll("ul.err-msg").empty();
if(pwd != cfmPwd){
$j("#ConfirmPassword").addClass("invalidPwd").nextAll("ul.err-msg").html("<li>Password does not match</li>");
//here id is passed as string
page_smooth_scroll("ConfirmPassword");
validPassword = false;
}
else{
$j("#ConfirmPassword").removeClass("invalidPwd").nextAll("ul.err-msg").empty();
validPassword = true;
}
}
return validPassword;
}





the image is below while debugging
passing string

receiving bool

Answer
if (target_id =! null) {

I think you mean a != b

Because a=!b means a = !b which means "assign the opposite boolean value", which will indeed turn anything into a boolean.

Next time if you think a function is "receiving a boolean", make sure to debug the value before running any statements. I'm sure it's still a string when going into the function.