1

Actually I am validating a form that has text, select, dropdown et-al fields. I have some of the fields that are mandatory and I have given them a class required(only textfields). Now I want to loop through all the form elements and check if that element has a class required, then append a * after that field. I have used each() method, but I don't get it to work exactly as how I want it to be.

My code looks like this:

function validate_form() {
    $("#mysubmit").each(function() {
        if($("form :text.required:text").val() == "" )
        {
            $("form :text.required:text").html("*");
            return false;
        }
        return true;
    });
}

where mysubmit is the id of my submit button.

I want to traverse the DOM elements one by one. Can anyone help as how do I validate this form. Thanks

singularity
  • 37
  • 1
  • 4

3 Answers3

1

As you said, you want to append the the '*'. You were trying to insert it inside.

We'll create a span with class="validation" Do it like this:

function validate_form() {
    var valid = true;
    $('form .required:text').each(function(){
       var $spanVal = $(this).next(); //Try to get the validation message (who has '*')
       if ($(this).val()!="" && $spanVal.is("span.validation")){ //If text has value
           $spanVal.remove(); //remove the asterisk
       }else if($(this).val()==""){ //If text is empty           
           if(!$spanVal.is("span.validation")){ //Create a validation message if it doesn't exist
              $('<span class="validation">*</span>').insertAfter(this);
           }
           valid = false;
       } 
    });
    return valid;
}

Hope this helps. Cheers.

Edgar Villegas Alvarado
  • 18,204
  • 2
  • 42
  • 61
  • I added a bit to validate this for whitespaces, but it doesn't validate the whitespaces. where am I wrong here: else if($(this).val()=="" || $(this).val().replace(/\s/g, '').length == 0) And Thanks for the Answer – singularity May 08 '11 at 07:39
0

this is how i solved my issue without

in the if statement remove the alert and .append the * :) think it should work

https://stackoverflow.com/a/40891000/5185974

Community
  • 1
  • 1
  • A link to a potential solution is always welcome, but please [add context around the link](http://meta.stackoverflow.com/a/8259/169503) so your fellow users will have some idea what it is and why it’s there. Always quote the most relevant part of an important link, in case the target site is unreachable or goes permanently offline. Take into account that being _barely more than a link to an external site_ is a possible reason as to [Why and how are some answers deleted?](http://stackoverflow.com/help/deleted-answers). – elixenide Nov 30 '16 at 16:05
0

You can use .after for appending a * after the required element, like so:

$('.required').after('<span>*</span>');

For iterating over all required fields you would do this:

$(.required).each(function(){
    //do something with this
    //inside this function 'this' is in turn each of the selected elements
    alert($(this).val());
});

jQuery.each iterates over all the elements in the selection it is applied on. In your case $("#mysubmit") is just one element (I assume the submit button). There is no need for it.
Here is a rewritten version of your code:

function validate_form() {
    var valid = true;
    $('form .required').each(function(){
       if ($(this).val()==''){
         $(this).after('<span>*</span>');
         valid = false;
       }
    });
    return valid;
}

Notes:

  • There is no need for $("#mysubmit").each as the logic inside your function does not depend on the submit button
  • Returning a value from the .each function like you tried does not work as you expect it. If you return false from the .each function it will simply stop iteration.
  • $("form :text.required:text") will match all text fields that have the class .required, not just one, as you are expecting.
Dan Manastireanu
  • 1,802
  • 1
  • 15
  • 18