Question

I'm building a single page web site with multiple forms scattered around it. I'm using Requirejs and jQuery and I'm trying to minimize the validation process to a single scrip, as so:

$("form").submit(function( event ) {
var empty_fields = [];
  $(this > "chck").each(function(){
    if($(this).val().length !=0 ) {
        return;
  }else{
    empty_fields.push($(this).attr('name'))
    $(this).css('border','2px solid red');
    event.preventDefault();}
})
    if(empty_fields){
        alert("The required field "+empty_fields+" is missing")
    }

});

Now the problem is that whenever I'm submitting a form (it doesn't matter which form) the function goes through all the child elements with "chck" (check) class.

What I've tried to do is to force the function to select ONLY the submitted form and check its child (".chck) and them only - Not the rest of the "chck" in other forms.

But I just can't seem to make it refer only to the form being submitted.

Any advice?

Was it helpful?

Solution

you can get the forms id, which is submitted with event.currentTarget.id

$("form").submit(function( event ) {
var empty_fields = [];
  $("#" + event.currentTarget.id + " .chck").each(function(){
    if($(this).val().length !=0 ) {
        return;
  }else{
    empty_fields.push($(this).attr('name'))
    $(this).css('border','2px solid red');
    event.preventDefault();}
})
    if(empty_fields){
        alert("The required field "+empty_fields+" is missing")
    }

});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top