I want to validate the form elements on click next buttoon in step form. I am using the folllowing code which is validating all the hidden fields also. Need help. Thanks in advance..
Here is my Code :
$('.msf-form .btn-next').on('click', function() {
var parent_fieldset = $(this).parents('fieldset');
var next_step = true;
parent_fieldset.find('.is_required').each(function() {
if( $(this).val() == "" ) {
$(this).focus().css('border','1px solid #F44336');
$(".error-messages-slct").text("Please Select an option in the list").fadeIn();
next_step = false;
}
else{
$(this).focus().css('border','0px solid #F44336');
$(".error-messages-slct").empty().fadeOut();
}
});
parent_fieldset.find('.is_required1').each(function() {
if( $(this).val() == "" ) {
$(this).focus().css('border','1px solid #F44336');
$(".error-messages-slct1").text("Select an option in the list").fadeIn();
next_step = false;
}
else{
$(this).focus().css('border','0px solid #F44336');
$(".error-messages-slct1").empty().fadeOut();
}
});
if( next_step ) {
parent_fieldset.fadeOut(400, function() {
$(this).next().fadeIn();
});
}
});
you can add :visible after the selectors. Use this reference..
Use it like this
Instead of going over each element of class '.is_required1' and '.is_required', you need to do it only for these element(s) which is(are) currently visible. You can use an additional class for this, or query the display property.
Taking minksmnm's suggestion into account, you could use find('.is_required:visible') instead of ``find('.is_required')` to only select the visible elements. Otherwide your find also gets the hidden ones and validates them too.
Related
For textboxes and numbers, If they are empty, We send the following error command very easily:
AJAX
parent_fieldset.find('input[type="text"], input[type="number"]').each(function() {
if( $(this).val() == "" ) {
$(this).addClass('input-error');
next_step = false;
}
else {
$(this).removeClass('input-error');
}
});
CSS
.input-error {
border-color: red;
}
But for select option, checkbox, radio tags, if they were empty, How should I do?
You may use something like this:
$(document).ready(function(){
$('#mySelectBox').each(function() {
if($(this).val() == -1)
$(this).addClass('input-error');
else
$(this).removeClass('input-error');
});
});
A fiddle example here. To clarify a bit, I assumed here that you'd have a "please select option" with the value -1 (so nothing was actually selected):
To verify if a combo box item has been selected, you can check the selectedIndex value.
With the checkbox, you can check its checked property.
Working example is at https://jsbin.com/hezemohali/edit?html,js,output
function verify() {
let selectCar = this.document.getElementById("car-brand");
if(selectCar.selectedIndex === 0)
selectCar.className = 'input-error';
else
selectCar.classList.remove('input-error');
let tc = this.document.getElementById("tc");
if (!tc.checked)
tc.parentNode.className = 'input-error';
else
tc.parentNode.classList.remove('input-error');
}
Here's my code
$('.f1 .btn-next').on('click', function() {
var parent_fieldset = $(this).parents('fieldset');
var next_step = true;
// navigation steps / progress steps
var current_active_step = $(this).parents('.f1').find('.f1-step.active');
var progress_line = $(this).parents('.f1').find('.f1-progress-line');
// fields validation
parent_fieldset.find('input[type="text"], select').each(function() {
if( $(this).val() == "" ) {
$(this).addClass('input-error');
next_step = false;
}
else {
$(this).removeClass('input-error');
}
});
// fields validation
Its a kind of Validation which i'm using in my Multi-step Form, here the input text field validation is working perfectly but for Select/Checkbox/Radio, its not working, Please help me to fix the code.
I already tried this code but it's not working for select field -
parent_fieldset.find('input[type="text"], select', '.sys').each(function() {
You're saying that you only want inputs whose type is text, so that's what you're getting. If you want every type of input, just take the type specification away from the selector, like this:
parent_fieldset.find(':input').each(function() {
}
Edit: the jQuery :input extension will include select elements, while input will not. The jQuery doc is here.
Try the following code.
parent_fieldset.find(':input').each(function() {
//Your code goes here.
}
//Try this one another way to validate form fields
var allFormData = $('#myForm').serializeArray();
for(var dataIndex = 0 ; dataIndex < allFormData.length ; dataIndex++){
if(allFormData[dataIndex].value == ""){
$("#myForm input[name="+allFormData[dataIndex].name+"]").addClass("input-error");
}else{
$("#myForm input[name="+allFormData[dataIndex].name+"]").removeClass('input-error');
}
}
So this is my final code which works perfectly with all select, radio, checkbox fields
parent_fieldset.find('input[type="text"], select', '.sys').each(function(key, value) {
I have a form where I'm using twitter typehead & the problem is whenever twitter typehead loads it creates another input field that is blank ¬ shown to user
Now i have this function to validate all inputs
var fields = $('#second_step input[type=text]');
var error = 0;
if (!$("input[name='career']:checked").val()) {
alert('Please Select yes or no'); return false;
}
fields.each(function(){
var value = $(this).val();
if( value.length<1 || value==field_values[$(this).attr('id')]) {
$(this).addClass('error');
$(this).effect("shake", { times:3 }, 50);
error++;
} else {
$(this).addClass('valid');
}
});
if (!$('#reg').valid()) {
return false;
}
Now due to that typehead input whic has no name or id it just have a certain class tt-hint & this input is read only how can i just skip this input from my above validation?
You can use jQuery's NOT function.
var fields = $('#second_step input[type=text]').not('.tt-hint');
You can filter out the fields with:
var fields = $('#second_step input[type=text]:not(.tt-hint)');
Your input has typeahead applied by using a class selector .typeahead.
So in your case you could use the :not pseudo-class selector to filter them out:
var fields = $('#second_step input[type=text]:not(.typeahead)');
That way you skip the typeahead fields.
Personally I would ignore disabled fields, since the user cannot correct them if there is an error. You say the input is read only so that would seem to correlate.
$('#second_step input[type=text]').filter(function(){ return !this.disabled; })
Try this :
fields.each(function(){
var value = $(this).val();
if($(this).hasClass('tt-hint') {
$(this).addClass('valid');
} else {
if( value.length<1 || value==field_values[$(this).attr('id')]) {
$(this).addClass('error');
$(this).effect("shake", { times:3 }, 50);
error++;
} else {
$(this).addClass('valid');
}
}
});
if (!$('#reg').valid()) {
return false;
}
How is it possible to display an alert with jQuery if I click the submit button and the value of the input field is empty?
<input type="text" id="myMessage" name="shoutbox_msg" size="16" class="field_nosize" maxlength="150">
<input id="submit" type="submit" name="submit_post" class="button_nosize" value="Senden" onclick="sendMessage(); clearInput();">
$('#submit').click(function(){
if($('#myMessage').val() == ''){
alert('Input can not be left blank');
}
});
Update
If you don't want whitespace also u can remove them using jQuery.trim()
Description: Remove the whitespace from the beginning and end of a string.
$('#submit').click(function(){
if($.trim($('#myMessage').val()) == ''){
alert('Input can not be left blank');
}
});
Better one is here.
$('#submit').click(function()
{
if( !$('#myMessage').val() ) {
alert('warning');
}
});
And you don't necessarily need .length or see if its >0 since an empty string evaluates to false anyway but if you'd like to for readability purposes:
$('#submit').on('click',function()
{
if( $('#myMessage').val().length === 0 ) {
alert('warning');
}
});
If you're sure it will always operate on a textfield element then you can just use this.value.
$('#submit').click(function()
{
if( !document.getElementById('myMessage').value ) {
alert('warning');
}
});
Also you should take note that $('input:text') grabs multiple elements, specify a context or use the this keyword if you just want a reference to a lone element ( provided theres one textfield in the context's descendants/children ).
Also you can try this, if you want to focus on same text after error.
If you wants to show this error message in a paragraph then you can use this one:
$(document).ready(function () {
$("#submit").click(function () {
if($('#selBooks').val() === '') {
$("#Paragraph_id").text("Please select a book and then proceed.").show();
$('#selBooks').focus();
return false;
}
});
});
Check empty input with removing space(if user enter space) from input using trim
$(document).ready(function(){
$('#button').click(function(){
if($.trim($('#fname').val()) == '')
{
$('#fname').css("border-color", "red");
alert("Empty");
}
});
});
You could create a function that checks every input in an input class like below
function validateForm() {
var anyFieldIsEmpty = jQuery(".myclass").filter(function () {
return $.trim(this.value).length === 0;
}).length > 0
if (anyFieldIsEmpty) {
alert("Fill all the necessary fields");
var empty = $(".myclass").filter(function () {
return $.trim(this.value).length === 0;
})
empty.css("border", "1px solid red");
return false;
} else {
return true;
}
}
What this does is it checks every input in 'myclass' and if empty it gives alert and colour the border of the input and user will recognize which input is not filled.
Use this instead because just trying to check if the value is not equal to an empty string won't help if there are multiple spaces.
('#submit').onclick = function(){
let count = 0;
let notEmpty = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";
for(let i=0; i < $('#myMessage').value.length; i ++){
for(let j = 0; j < notEmpty.length ; j++){
if($('#myMessage').value[i]== notEmpty[j]){
count += 1;
}
}
}
if(count==0){
alert("You cannot leave this blank");
}
}
So I'm trying to style a <textarea> tag to highlight when it has more than one character typed in. (For a contact form). When someone is filling out the form, the fields will all highlight green to let them know its valid. I'm very new to JS and jQuery in general but I'm pretty sure this is supossed to work. I can use the $('#message').addClass('valid') by itself and it will apply the class, but when I add the if/else statement, nothing works. Here is the script
\\ Begin Highlight Code
var $messageval = $('#message').val()
if ($messageval.length != 0 ){
$('#message').addClass('valid');
}
else ($messageval.length = 0 ){
$('#message').removeClass('valid');
}
});
I've been googling for hours and I can't find anything to dynamically add and remove classes based on a text length variable.
Thanks
You are missing else if
if ($messageval.length != 0 ){
$(this).addClass('valid');
}
else if($messageval.length == 0 ){ //<-- Here
$('#message').removeClass('valid');
}
Basically you can just have
if ($messageval.length != 0 ){
$('#message').addClass('valid');
}
else { //<-- Here
$('#message').removeClass('valid');
}
I guess this is what you are looking for:-
$(function(){
$('#message').on('keyup', function () {
var $messageval = $.trim($(this).val()); //$.trim here to avoid whitespace preventing validation.
if ($messageval.length != 0) {
$(this).addClass('valid'); //this here represent the textarea dom element, and $(this) is the jquery wrapper.
} else {
$(this).removeClass('valid');
}
});
});
Fiddle
$(document).ready(function(){
$("#message").keyup(function(){
var messageval = $('#message').val();
if (messageval.length > 1) {
$('#message').addClass('valid');
} else {
$('#message').removeClass('valid');
}
});
});
change your code to this
$(document).ready(function(){
$('#message').trigger('change');//if you initially want to check the textarea
$('#message').on('change', function(){
var $messageval = $(this).val();
if ($messageval.length != 0 ){
if (!$(this).hasClass("valid")) {
$(this).addClass("valid");
}
}
else ($messageval.length == 0 ){
if ($(this).hasClass("valid")) {
$(this).removeClass("valid");
}
}
});
});
Cheers!