Robert
Robert

Reputation: 10380

jQuery Form Validation not showing error upon failure

Note: this is a jQuery coding exercise so I am not allowed to use plugins or other modules.

I made a simple, typical form and want to check to make sure that the form fields are entered and not left blank. If they are, the appropriate message appears showing an error. I have not succeeded in this so far.

After this I will add a function to make sure a valid email is entered.

My form:

<form id="myForm">
          <input type="text" placeholder="Email" id="email" name="email">
          <span class="error">Email not entered</span><br />
          <input type="password" placeholder="Password" id="pword" name="pword">
          <span class="error">Password not entered</span><br />
          <input type="text" placeholder="First Name" id="fname" name="fname">
          <span class="error">First Name not entered</span><br />
          <input type="text" placeholder="Last Name" id="lname" name="lname">
          <span class="error">Last Name not entered</span><br />
          <input type="submit" value="Submit">
    </form>

jQuery:

$(document).ready(function(){

    // field mapping
    var form_fields = {
        'email' : 'email',
        'pword' : 'password',
        'fname' : 'first name',
        'lname' : 'last name'
    };

    // make sure form fields were entered
    $('#myForm').on('submit', function(e){
        e.preventDefault();

        for (var field in form_fields) {
            if (!$('#' + field).val()) {
                $('#' + field + ' span').addClass('.error_show');
            }
        }

    });

});

CSS:

.error {
    display: none;
}

.error_show {
    display: inline-block;
    color: red;
    margin-bottom: 1em;
}

Upvotes: 3

Views: 95

Answers (1)

Guruprasad J Rao
Guruprasad J Rao

Reputation: 29683

Everything works fine except the way you are selecting you subsequent span of the element plus the way you are adding the error class. You can use .next to find the next element of the input validated and then I would like to mention the below changes to be done and here is the DEMO

for (var field in form_fields) {
   if (!$('#' + field).val()) {
        $('#' + field).next('.error').addClass('error_show'); //get the next element with class .error
   }
}

The way you were adding class was .addClass('.error_show'); and here . should not be given while adding class since its not a selector and is a classname.


UPDATE

Your selector will work if span was child of '#'+field and since it was sibling it wasn't able to find the particular span with the way you were using it.. Alternatively you could have used #' + field +' ~ span' or #' + field +' + span'. DEMO HERE. Know more about different selectors here

Upvotes: 4

Related Questions