Reputation: 459
I have an html form with input types texts and radio button with class = required. I am trying to validate the form. On submit of the form I need to validate the form and if it returns false, I need to add a new div (text "Please fill in the required field") and display it below the field in red. If the user fills in that field, it should become green color or red color should disappear. jQuery is in separate js file. So on click of the submit button I am doing the following
$('#test_form .required').filter(':visible').each(function() {
var input = $(this);
if($(this).is(':empty')){
$(this).css("border","2px solid #FF0004");
$(this).after('<div>Please fill in the required field</div>');
return = false;
}else{
return true;
}
});
There are couple of problems occurring now. 1. required text is coming below the fields.I need that in red color and font size - 10px. So how can I add css to the newly added div? 2. Consider there is a radio group of 5 radio button. So I need the Required text only if atleast one is not selected and display the text below that radio group. Now the Required text is coming for all the radio buttons. 3. Also if the user clicks submit 4 times, the text gets added 4 times for each field. I think this we can handle using a flag
Can anyone please guide me on this?
Upvotes: 1
Views: 1613
Reputation: 1200
you have to set errorPlacement section of jQuery validate function.
$("#form").validate({
rules: {
name: {
required: true
},
firstname: {
required: true
}
},
messages: {
name: {
required: "Enter name"
},
firstname: {
required: "Enter firstname"
}
},
errorPlacement: function ($error, $element) {
var name = $element.attr("name");
$("#error" + name).append($error);
}
});
Example: http://jsfiddle.net/R3aEQ/
Upvotes: 0
Reputation: 2475
- required text is coming below the fields.I need that in red color and font size - 10px. So how can I add css to the newly added div?
What about adding css ? Just add a class to the newly created div. That could help you better position your div and add other css.
Modify
$(this).after('<div>Please fill in the required field</div>');
to
$(this).after('<div class="info">Please fill in the required field</div>');
And in CSS
<style>
.info{
background:#FFB0B0;
color:#FF0000;
}
</style>
2.
Consider there is a radio group of 5 radio button. So I need the Required text only if atleast one is not selected and display the text below that radio group. Now the Required text is coming for all the radio buttons.
3.
Also if the user clicks submit 4 times, the text gets added 4 times for each field.
Adding a flag could fix these problems
Upvotes: 1