Eckstein Eckstein - 4 months ago 24
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'),
parent;

// Remove any existing messages
for (var i = 0; i < errorMessages.length; i++) {
errorMessages[i].parentNode.removeChild(errorMessages[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');
$(fields[i]).get(0).setCustomValidity(message);
}

//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 +
"</div>");
}

Answer

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
    $(this)[0].setCustomValidity(message);
});

// 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>");
});
Comments