S. Andersson S. Andersson - 5 months ago 10
jQuery Question

ERROR in jQuery for some reason and I can't figure out why

Could someone take a look? I believe there is something wrong with the jquery source code but I can't come to a more specific explanation than that.



https://codepen.io/SebastianSapien/pen/wWJXMB



app.js:

//Hide hints
$("form span").css("display", "none");

//create som variables to make the code easier to follow
var $password = $("#password");
var $confirmPassword = $("#confirmPassword");

//when focusing (clicking) on the password text input, show the
//hints until the length of the input reaches 8.

//specifies whether the password specified is long enough
function passwordIEnough() {
return $(this).val().length > 8;
}

//specifies if the password and confirm password boxes are equal
function passwordsAreEqual() {
return $password.val() === $confirmPassword.val();
}


function passwordEvent() {
if ( passwordIsEnough() ) {
$(this).next().css("display", "none");
} else {
$(this).next().css("display", "inline-block");
}
}

function confirmPasswordEvent() {
if ( passwordsAreEqual() ) {
$(this).next().css("display", "none");
} else {
$(this).next().css("display", "inline-block");
}
}


html:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Dropdown</title>
<link rel="stylesheet" href="css/style.css" charset="utf-8">
</head>
<body>

<form action="#" method="post">
<h2>Professional Form</h2>
<label for="username">Username</label>
<input type="text" id="uname" name="username">

<label for="password">Password</label>
<input type="password" id="password" name="password">
<!-- <div class="arrow-left"></div> -->
<span>Atleast 8 characters</span>

<label for="confirmPassword">Confirm Password</label>
<input type="password" id="confirmPassword" name="confirmPassword">
<!-- <div class="arrow-left"></div> -->
<span>Please confirm your password</span>

<input type="submit" value="Submit" id="submit">
</form>


<script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ=" crossorigin="anonymous"></script>
<script src="js/app.js" type="text/javascript" charset="utf-8"></script>
</body>
</html>



$password.focus(passwordEvent).keyup(passwordEvent).focus(confirmPasswordEvent).keyup(confirmPasswordEvent);

$confirmPassword.focus(confirmPasswordEvent).keyup(confirmPasswordEvent);


What the console says:


Uncaught TypeError: Cannot read property 'toLowerCase' of undefined
jquery-1.12.4.min.js:4

Answer

The problem is that "this" in your case is a reference to the window, not to the textbox as you are expecting. $(this) will only work inside of a bound event handler. Try using a different method of gaining access to your textbox like $("#password").val(), or use $("#password").focus(function(){}) for your logic.

Comments