Loop through Form Elements with Specefic Class
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
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.
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 returnfalse
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.
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
精彩评论