Javascript Question

Bootstrap Modal Form Validation Issue

I am working with form inside Modal. I want to validate it but it's not working.

Details:

Instead of having a Submit Button, i have an anchor link named Login to submit my form using ajax. But before that i want to make some validations.
I am facing error in console

lendingPage.js:32 Uncaught TypeError: username.removeClass is not a function


Please help me in finding my mistake.

lendingPage.js

$('#login_Modal').click(function (e){
e.preventDefault();
var username = $('#loginUsername').val();
var password = $('#loginPassword').val();

// Check if there is an entered value
if(username.length>0) {
// Remove the errors highlight
username.removeClass('has-error').addClass('has-success');

} else {
// Add errors highlight
username.removeClass('has-success').addClass('has-error');

// Stop submission of the form
e.preventDefault();

}

$.ajax({
url: "form_login_process.php",
type: 'POST',
data:{'Username':username,'Password':password},
success: function (data)
{
if(data === "true")
{
}
else if(data === "false")
{
}
},
});
});


Modal

<form role="form" method="post" id="login_Modal_checks">
<div class="form-group has-error">
<label for="username"><span class="glyphicon glyphicon-user"> </span>Username</label>
<input type="text" class="form-control" name="loginUsername" id="loginUsername" placeholder="Enter username">
</div>

<div class="form-group has-error">

<label for="psw"><span class="glyphicon glyphicon-pencil"></span> Password</label>

<input type="password" class="form-control" name="loginPassword" id="loginPassword" placeholder="Enter password">
<i style="cursor: pointer" id="seePass" title="Click here to see password" class="glyphicon glyphicon-eye-open"></i>

</div>
<div class="checkbox">
<label><input type="checkbox" value="" checked>Remember me</label>
</div>

<a id="login_Modal" class="btn btn-success btn-block"><span class="glyphicon glyphicon-off"></span> Login</a>

</form>

Answer

variable username has just a value from input box.

For changing class you want to do something like below...

        if($("#loginUsername").val() === '') {
            $("#loginUsername").parent().addClass('has-error');
            $("#loginUsername").focus();
            errCount++;
        } else {
            $("#loginUsername").parent().removeClass('has-error').addClass('has-success');
            if(errCount > 0) {
                errCount--;
            }
        }

and if you want to use username variable then, use

var username = $("#loginUsername");

Then you can treat username as element variable. and to check value you can use username.val()

and to change parent class

$("#loginUsername").parent().removeClass('has-error').addClass('has-success');

Also see that you need to use .parent as username's parent element has that class and you want to change that.

Comments