Valentine Valentine - 3 months ago 10
HTML Question

Optimization of the form of validation using jQuery

I want to do validation, which displays an error message in the placeholder of the input.
I write code to check the 1 form field, and change its placeholder if it's empty. How can this be optimized for three fields?

$(document).ready(function() {
$("#submit").click(function() { if($("#name").val()==''||$("#name").val()==null){ $("#name").val("").attr("placeholder","An error occured!").addClass("changePlaceColor1").addClass("changePlaceColor2").addClass("changePlaceColor3").addClass("changePlaceColor4"); } }) })


here is my code in the codepen

Also want to do that to these changes remain until you press input.

Answer

just add a class="validation" to all your fields that need to be validated, and change your js to this

$(document).ready(function() {
  $("#submit").click(function(e) {
    $(".validation").each(function(){
        if($(this).val()==''||$(this).val()==null){
          $(this).val("")
            .attr("placeholder","An error occured!")
            .addClass("changePlaceColor1")
            .addClass("changePlaceColor2")
            .addClass("changePlaceColor3")
            .addClass("changePlaceColor4");
            e.preventDefault();
          }
    });
  })
})

No reason to add validation for each field sepperatly, add a basic validation code and loop through all applicable fields. Less time the same piece of code you have, the better your code is

Comments