Dương Quang Thọ Dương Quang Thọ - 13 days ago 6
jQuery Question

Please help about create error messages validate form input with JQuery

I have the register form as below:

<div class="form">
<form class="register-form" name="register-form">
<ul class="errorMessages"></ul>
<div class="user-name">
<input class="wrap" name="firstname" type="text" placeholder="firstname" required/>
<input class="wrap" name="lastname" type="text" placeholder="lastname" required/>
</div>
<input name="password" type="password" placeholder="password" autocomplete="off" required/>
<input name="email" type="text" placeholder="email address" autocomplete="off" required/>
button class="btn-signup" type="submit">Create</button>
<p class="message">Already registered? <a href="#">Sign In</a></p>
</div>


I create JQuery code check if input is blank, this will create error message"

$(function() {
var createAllErrors = function () {
var form = $(".register-form");
var errorList = $('ul.errorMessages', form);

var showAllErrorMessages = function () {
errorList.empty();

form.find(':invalid').each(function (index, node) {
var label = $('input').attr('name');
var message = node.validationMessage || 'Invalid value.';
errorList
.show()
.append('<li><span>' + label + ': ' + '</span>' + message + '</li>');
});
};
$('input[type=submit], button', form).on('click', showAllErrorMessages);
};
$('form').each(createAllErrors);
});


But when I press button I have result:
enter image description here

Any problem about label variable? or on form find invalid input? Please help me to solve this? thanks.

Answer

The error is inside your each loop. You're never using the current index, and instead you requery the whole dom in search for input elements. Whenn you call getter functions on a jQuery collection, jQuery will return the attribute of the first element inside the collection. In your case this is the firstname input element. Use the current element of the each loop instead:

form.find(':invalid').each(function (index, node) {

  // WRONG: This will always return firstname
  //var label = $('input').attr('name');

  // RIGHT: Access the current element inside each loop
  var label = $(node).attr('name');

  // ...
});
Comments