Eckstein Eckstein - 1 year ago 88
jQuery Question

How to do this the with Jquery instead of javascript

I've been trying to convert this section of script to jQuery instead of vanilla javascript, but I'm not sure how to loop through the elements with jQuery. Basically, I'm grabbing a data attr value from each field to be used as an error message that displays near the field.
This is all inside a click event on the submit button, FYI

What's the jQuery way?

//Set some variables
var invalidFields = $(form).querySelectorAll(':invalid'),
errorMessages = $(form).querySelectorAll('.error-message'),

// Remove any existing messages
for (var i = 0; i < errorMessages.length; i++) {

//Get custom messages from HTML data attribute for each invalid field
var fields = form.querySelectorAll('.sdForm-input');
for (var i = 0; i < fields.length; i++) {
var message = $(fields[i]).attr('data-ErrorMessage');

//Display custom messages
for (var i = 0; i < invalidFields.length; i++) {
parent = invalidFields[i].parentNode;
parent.insertAdjacentHTML('beforeend', '<div class='error-message'>' +
invalidFields[i].validationMessage +

Answer Source

I converted your code one-to-one to jQuery. But there might be other ways, when i will know where form, setCustomValidity and validationMessage is coming from.

var $form = $(form);

// Remove any existing messages
$(".error-message", $form).remove();

// Get custom messages from HTML data attribute for each invalid field
$(".sdForm-input", $form).each(function() {
    var message = $(this).attr('data-ErrorMessage');

    // i don't know where the 'setCustomValidity' function is coming from
    // this is a custom function

// Display custom messages
$(":invalid", $form).each(function() {
    // i don't know where 'validationMessage' is comig from
    // this is a custom property
    $(this).parent().append("<div class='error-message'>" + $(this)[0].validationMessage + "</div>");
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download