jQuery button validate part of a form at a time - javascript

Sorry if I did not explain my problem clearly.
I have a form with multiple tables for users inputs.
I use next and back buttons to hide and show different tables in order to guide users.
Now the problem is:
How do I use next button to validate current active table inputs? For example, every time a user click next, it will check if all the fields are filled?
Here is a broken DEMO. Thanks for any comments!
HTML
<form method="post" id="form1" action=index.html>
<table>
<H4 align="center" id="id_tab">
| Chemical |
Crop |
Physical |
</H4>
</table><br>
<table class="tab tab_Chemical" border="0">
<tr>
<th><label for="id_wat_hl">Water Column Half life (days):</label></th>
<td><input type="text" name="wat_hl" id="id_wat_hl" /></td>
</tr>
</table>
<table class="tab tab_Crop" border="0" style="display:none">
<tr>
<th><label for="id_zero_height_ref">Zero Height Reference:</label></th>
<td><input type="text" name="zero_height_ref" id="id_zero_height_ref" /></td>
</tr>
</table>
<table class="tab tab_Physical" border="0" style="display:none">
<tr>
<th><label for="id_mas_tras_cof">Mass Transfer Coefficient (m/s):</label></th>
<td><input type="text" name="mas_tras_cof" id="id_mas_tras_cof" /></td>
</tr>
</table>
<table align="center">
<tr>
<td><input class="back" type="button" value="Back" /></td>
<td><input class="next" type="button" value="Next" /></td>
<td><input class="submit" type="submit" value="Submit" /></td>
</tr>
</table>
</form>
JS
$(document).ready(function() {
var tab_pool = ["tab_Chemical", "tab_Crop", "tab_Physical"];
var visible = $(".tab:visible").attr('class').split(" ")[1];
var curr_ind = $.inArray(visible, tab_pool);
$(".submit").hide();
$(".back").hide();
$('.next').click(function() {
if (curr_ind < 2) {
$(".tab:visible").hide();
curr_ind = curr_ind + 1;
$("." + tab_pool[curr_ind]).show();
$(".submit").hide();
$(".back").show();
}
if (curr_ind == 2) {
$(".submit").show();
$(".next").hide();
}
});
$('.back').click(function() {
if (curr_ind > 0) {
$(".tab:visible").hide();
curr_ind = curr_ind - 1;
$("." + tab_pool[curr_ind]).show();
$(".submit").hide();
$(".next").show();
}
if (curr_ind == 0) {
$(".back").hide();
}
});
$(".next").click(function() {
$(".tab tab_Chemical").validate({
rules: {
wat_hl: "required"
}
})
})
$(".next").click(function() {
$(".tab tab_Crop").validate({
rules: {
zero_height_ref: "required"
}
})
})
$(".next").click(function() {
$(".tab tab_Physical").validate({
rules: {
mas_tras_cof: "required"
}
})
})
});

Add validation using the form
var validator = $('form').validate({
ignore: 'input[type="button"],input[type="submit"]',
rules: {
wat_hl: {
required: true
},
zero_height_ref: {
required : true
},
mas_tras_cof: {
required: true
}
}
});
Then in the next handler
$('.next').click(function () {
var tab = $(".tab:visible");
var valid = true;
$('input', tab).each(function(i, v){
valid = validator.element(v) && valid;
});
if(!valid){
return;
}
if (curr_ind < 2) {
$(".tab:visible").hide();
curr_ind = curr_ind + 1;
$("." + tab_pool[curr_ind]).show();
$(".submit").hide();
$(".back").show();
}
if (curr_ind == 2) {
$(".submit").show();
$(".next").hide();
}
});
Demo: Fiddle
Explanation
var valid = true: a flag to keep the state of the tab through the iteration process
$('input', tab).each: Iterate through each inputs element in the current tab
validator.element(v) validate each element in the tab
valid = validator.element(v) && valid: update the state of the tab

What about this ?
var isOpenedTabValid = $(".tab:visible :input").valid();

I have an implementation to get this same result. I have added div elements with role="form" parameter. And then validates elements on each div as it is like a form while the main form is still wrapping around.
<form action="#" id="myForm" role="form" data-toggle="validator" method="post">
<div id="form-step-0" role="form" data-toggle="validator"><!-- Input elemets --></div>
<div id="form-step-1" role="form" data-toggle="validator"><!-- Input elemets --></div>
<div id="form-step-2" role="form" data-toggle="validator"><!-- Input elemets --></div>
</form>
And this jQuery code to check if there is any error in a particular div
var elmForm = $("#form-step-0");
elmForm.validator('validate');
The following code will check if there is any error input raised in a particular div
var elmErr = elmForm.children('.has-error');
if(elmErr && elmErr.length > 0){
// Error elements found, Form validation failed
return false;
}
And when you want to validate the whole form just use the normal code
var elmForm = $("#myForm");
elmForm.validator('validate');
var elmErr = elmForm.find('.has-error');
if(elmErr && elmErr.length > 0){
alert('Oops we still have error in the form');
return false;
}else{
alert('Great! we are ready to submit form');
elmForm.submit();
return false;
}
Here is the source file on GitHub
Here is a Demo implemeation

You are calling the validate method for each table every time the next button is clicked. Instead, you only want to call validate if the table is visible. Since you are already tracking which table should be visible with your curr_ind, I'd suggest using it to know which table to validate and only calling validate for the visible table.

Related

form submit goes to wrong page in wordpress

I created a page which collect few information and when submit it loads to completely wrong page even though URL is correct.
Here is my script
<script type="text/javascript">
jQuery(document).ready(function () {
jQuery(".ch1").change(function () {
jQuery(".ch1").prop("checked", false);
jQuery(this).prop("checked", true);
});
jQuery(".ch2").change(function () {
jQuery(".ch2").prop("checked", false);
jQuery(this).prop("checked", true);
});
jQuery("#tour_date").datepicker({
dateFormat: "yy-mm-dd",
showOn: "button",
buttonText: "Select Date",
buttonImageOnly: true,
buttonImage: "http://jqueryui.com/resources/demos/datepicker/images/calendar.gif",
});
});
function validateForm() {
var children = jQuery("#child_cnt").val();
var adlt_cnt = jQuery("#adlt_cnt").val();
var tour_date = jQuery("#tour_date").val();
if (children == "") {
alert("Please enter No. of children");
return false;
}
if (adlt_cnt == "") {
alert("Please enter No. of adults");
return false;
}
if (tour_date == "") {
alert("Please enter tour date");
return false;
}
if (!validateTripTypes()) {
alert("Please select a trip type");
return false;
}
if (!validateServices()) {
alert("Please select a service");
return false;
}
}
function validateTripTypes() {
if (jQuery('.ch1:checked').length > 0) {
return true;
} else {
return false;
}
}
function validateServices() {
if (jQuery('.ch2:checked').length > 0) {
return true;
} else {
return false;
}
}
</script>
[vc_section][vc_column_text]
<form method="post" name="page1_form" onsubmit="return validateForm()" action="[insert_php] bloginfo('url'); [/insert_php]/new-tour-booking-next2/">
<label>No. of Children:</label> <input name="child_cnt" size="10" type="number" id="child_cnt"/>
<label>No. of Adults:</label> <input name="adlt_cnt" id="adlt_cnt" size="10" type="number" />
<label>Tour Date:</label> <input name="tour_date" id="tour_date" size="10" type="text" placeholder="Select Date"/>[/vc_column_text][/vc_section]
[insert_php]
$wp_session = WP_Session::get_instance();
$wp_session['child_cnt'] = 0;
global $wpdb;
$trip_types = $wpdb->get_results(
$wpdb->prepare("SELECT * FROM jtb_trip_types WHERE status = %d", array(1))
);
[/insert_php]
[vc_row][vc_column][vc_text_separator title="Type of Trip" title_align="separator_align_left"][/vc_column][/vc_row][vc_section][vc_column_text]
[insert_php]
$trip_type_list = "";
foreach ($trip_types as $trip_type) {
$trip_type_list .= '<input name="trip_type_list[]" size="10" type="checkbox" class="ch1" value="'.$trip_type->id.'" /><label>'.$trip_type->trip_type_name.'</label>
';
}
echo $trip_type_list;
[/insert_php]
[/vc_column_text][/vc_section][vc_row][vc_column][vc_text_separator title="Services" title_align="separator_align_left"][/vc_column][/vc_row][vc_row][vc_column][vc_column_text]
<input name="services_list[]" size="10" type="checkbox" class="ch2" value="1"/> <label>Vehicles</label>
<input name="services_list[]" size="10" type="checkbox" class="ch2" value="2"/> <label>Hotels</label>
<input name="services_list[]" size="10" type="checkbox" class="ch2" value="3"/> <label>Both</label>
[/vc_column_text][/vc_column][/vc_row][vc_row][vc_column][vc_btn title="Next" name="btn_next_form_1" type="submit" align="left"][/vc_column][/vc_row]
[insert_php]
//echo count($trip_types);
[/insert_php]
</<form>
It redirect to the correct URL. Which is this one http://www.jaudatravels.com/new-tour-booking-next2/
But it loads this page data even though URL is correct. http://www.jaudatravels.com/tours/
NB: This happens only when we submit the from through this page. http://www.jaudatravels.com/new-tour-booking/
Is there any reason for this behaviour?
The problem is your custom form & the right side search form both have been bind to a single submit event.
That is the reason the data getting loaded is not the one which you are expecting even though URL is correct because the URL is just to display the processing happens at the server side.
Solution:
There is a syntax error in ending form: </<form> rectify it
Or Just remove that search widget & try.
And also always be careful about the form structure when form start there must not be any div or a table interruption like
<div>
<form>
<input type="text" name="my_input"/>
</div>
</form>
Or
<table>
<tr>
<form>
<th><td><input type="text" name="my_input"/></td></th>
</tr>
</table>
</form>
So always include entire element (like div Or table Or anything) within the form so that no interruptions happen.

issue with form validation including input file

I'm having this very simple form to enter user name and choose a file to upload. User name is required but file is not. It's styled and has a function to check file type and size before submitting the form. If you choose a wrong file the function will work and the submit button will be disabled. If you don't choose a file the user name validation won't work. If you click in the text input then blur it will go red but the form will submit.
JSFIDDLE
HTML
<form method="post" class="contact" onsubmit="return validate();" enctype="multipart/form-data">
<table cellspacing="30">
<tr>
<td>
<label id="userlabel">user name</label>
<input type="text" id="user" name="username" onblur="checkUser()"></td>
</tr>
<tr>
<td>
<div id="FileUpload">
<input type="file" size="4" id="BrowserHidden"
onchange="getElementById('FileField').value = getElementById('BrowserHidden').value;" name="pic" />
<div id="BrowserVisible"><input type="text" id="FileField" /></div>
</div>
</td>
</tr>
<tr>
<td><input type="submit" name="send" id="save" value="send" /></td>
</tr>
</table>
</form>
JS
function checkUser(){
var userlen = $("#user").val().length;
if(userlen<4){
$("#userlabel").css("color","rgb(224, 19, 19)");
return false;
}
else{
$("#userlabel").css("color","#000");
return true;
}
}
$("#BrowserHidden").change(function (e) {
var file = this.files[0];
var name = file.name;
var extension = name.substr((name.lastIndexOf('.') + 1));
var str = 'doc,docx,pdf';
if (str.indexOf(extension) > -1) {
console.log('y');
size = file.size;
console.log(size);
if (size > 10000000) {
alert('file size is larger than 10 MB');
$("#save").attr("disabled", "disabled");
return false;
}
else {
$("#save").removeAttr("disabled");
return true;
}
}
else {
alert('file type is not allowed');
$("#save").attr("disabled", "disabled");
return false;
}
});
function validate(){
$.each($('form :input'),function(){
$(this).blur().change();
});
if(!checkUser() ){
return false;
}
else{
return true;
}
}
This is how you can make it working:
change your submit button to normal one and add onclick attribute to it
remove onsubmit attribute from your form tag
change your validate() function to submit form if checkUser() returns true
That's it!
Fiddle
Hope that worked for you!

JavaScript -- not validating for blank fields

I have the following JavaScript function that is not supposed to allow blank fields to be sent to my back end code, but it's doing it anyway. Even if one or both of my fields is empty, this code is sending 2 blank values. (It works just fine if they're both filled in.) It's also not making my error messages appear. Can anyone help me? Here is my JavaScript.
function submitForm() {
var allValid = true;
var name = $("#name").val();
var comment = $("#comment").val();
if (name == null || name.length == 0) {
allValid = false;
$("#nameReq").css("visibility", "block");
} else {
$("#nameReq").css("visibility", "hidden");
}
if (comment == null || comment.length == 0) {
allValid = false;
$("#commentReq").css("display", "block");
} else {
$("#commentReq").css("display", "hidden");
}
if (allValid) {
clearForm();
$.ajax({
type : "post",
url : "writeComment",
data : "name=" + name + "&comment=" + comment,
success : function(response) {
},
error : function(error) {
}
});
document.getElementById('submit').disabled = true;
}
}
function clearForm() {
$("commentForm").reset();
}
Here is my form.
<form:form id="commentForm" method="post">
<table>
<tr>
<td>Name:<span style="display: none" id="nameReq">
<font style="font-weight: bold; color: red; visibility: hidden;">
<c:out value='Name required' /></font></span><br />
<input type="text" id="name" maxlength="30" /></td>
</tr>
<tr>
<td>Comment:<span style="display: none" id="commentReq">
<font style="font-weight: bold; color: red; visibility: hidden;">
<c:out value='Comment required' /></font></span><br />
<textarea id="comment" rows="20" cols="125" /></textarea></td>
</tr>
<tr>
<td><input id="submit" type="submit" value="Submit comment" onClick="submitForm()" /></td>
<td> </td>
</tr>
</table>
</form:form>
Your form will submit regardless of the action in your onclick function because the input button type is submit. If you'd like to only submit using your AJAX call, change the input to type="button".
Even if you'd like to submit without the ajax call, you can still use type="button" and submit the form using $('#commentForm').submit();
Your textarea is both self-terminating and has a closing tag. When I tried to run this, that confused it to the point that the onClick of the button was not run.

Jquery : prevent checkbox being unchecked

I'm attempting to only allow the user to check checkboxes in chronological order.
<table id="status">
<tr><td>Ready <input type="checkbox"></td></tr>
<tr><td>Set <input type="checkbox"></td></tr>
<tr><td>Go <input type="checkbox"></td></tr>
</table>
User is not allowed to uncheck the checkboxes and only allowed to click in the order Ready, Set, Go. For this i can only add events to checkboxes and not the td element.
$("#status input[type='checkbox']").on("change",function(event) {
if($(this).parents("tr:first").prev("tr").length==0) {
var first_checkbox = 1;
} else {
var first_checkbox = 0;
}
if($(this)
.parents("tr:first")
.prev("tr")
.find("input[type='checkbox']")
.is(":checked") || first_checkbox==1) {
$(this).attr("checked",true);
}
}
});
This only allows a click if the previous checkbox is clicked but how do i prevent a checkbox being unclicked?
Programatically this is quite simple:
Disable all checkboxes, except for the first one, at runtime
When a checkbox is checked, disable it after that, and enable the next checkbox
See the demo below, it should work as intended:
$(function() {
$('#status input[type="checkbox"]').each(function() {
// Disable all but the first checkbox
if ($(this).closest('tr').index() !== 0) {
$(this).prop('disabled', true);
}
}).on('change', function() {
// Once checked, disable it
$(this).prop('disabled', true);
// Then enable the next checkbox
$(this).closest('tr').next('tr').find('input[type="checkbox"]').prop('disabled', false);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="status">
<tr>
<td>Ready
<input type="checkbox" />
</td>
</tr>
<tr>
<td>Set
<input type="checkbox" />
</td>
</tr>
<tr>
<td>Go
<input type="checkbox" />
</td>
</tr>
</table>
Warning: When input elements are disabled, their values are not sent when a form is submitted. You might want to disable interaction in other ways instead of relying on the boolean attribute disabled. #Rich has an alternative solution of disabling pointer events, which I have modified my demo for. I have added some CSS styles so users can tell if a checkbox is clickable or not:
$(function() {
$('#status input[type="checkbox"]').each(function() {
// Disable all but the first checkbox
if ($(this).closest('tr').index() !== 0) {
$(this).closest('tr').addClass('disabled');
}
}).on('change', function() {
// Once checked, disable it
$(this).closest('tr').addClass('disabled checked');
// Then enable the next checkbox
$(this).closest('tr').next('tr').removeClass('disabled');
});
});
tr {
background-color: #BEEB9F;
}
tr.disabled {
background-color: #FFFF9D;
}
tr.disabled.checked {
background-color: #97C4A6;
}
tr.disabled input {
pointer-events: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="status">
<tr>
<td>Ready
<input type="checkbox" />
</td>
</tr>
<tr>
<td>Set
<input type="checkbox" />
</td>
</tr>
<tr>
<td>Go
<input type="checkbox" />
</td>
</tr>
</table>
This should do exactly what your looking for.
$("#status input[type='checkbox']").on("click", function (e) {
var checkbox = $(this);
if (checkbox.is(":checked") {
// do the confirmation thing here
e.preventDefault();
return false;
}
});
You can use disabled attribute for the checkboxes and enable or disable them occasionally:
$(document).on('click', 'input', function(e) {
var that = $(this);
var id = that.attr('id');
var set = $('#set');
var go = $('#go');
if (id == 'ready') {
if (!set.is(':checked') && !go.is(':checked')) {
if (that.is(':checked')) {
set.removeAttr('disabled');
} else {
set.attr('disabled', true);
go.attr('disabled', true);
}
} else {
e.preventDefault();
}
}
if (id == 'set') {
if (!go.is(':checked')) {
if (that.is(':checked')) {
go.removeAttr('disabled');
} else {
go.attr('disabled', true);
}
} else {
e.preventDefault();
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table id="status">
<tr><td>Ready <input id="ready" type="checkbox"></td></tr>
<tr><td>Set <input id="set" type="checkbox" disabled></td></tr>
<tr><td>Go <input id="go" type="checkbox" disabled></td></tr>
</table>
Just change
$(this).attr("checked",true); to $(this).prop('checked', true)
and add the following:
if( first_checkbox != 1 && !$(this).parents('tr:first').prev('tr').find('input[type="checkbox"]').is(":checked")) {
$(this).prop('checked', false);
}
Here is an example without disabling the checkboxes: https://jsfiddle.net/t338vu33/
The checkboxes has to be unchecked or checked in a chronological order:
var current = 0;
$("#status input[type='checkbox']").on("change", function(event) {
var selectedIndex = $('input:checkbox').index( $(this) );
if ($(this).is(":checked")) {
if(selectedIndex != current)
$(this).prop('checked', false);
else
current ++;
}
else{
if(selectedIndex != current-1)
$(this).prop('checked', true);
else
current --;
}
});

Are there any very Simple JQuery Validation?

Hi I'm looking to add some simple validation to a form.
There are 2 textboxes which the user is expected to enter only numbers and it must be greater than zero. The jquery code is in it's own file (the form consists of html / jquery / php). The first number is for 'previous age' and the second number is for 'current age'. For example, if the user enters '0' in either textbox, an alert or message box should appear informing them that they need to enter a number greater than zero. Anything other than a number greater than zero entered into the textbox should result in the alert message.
As a side note, the .php file is used only for the calculation/math once the user has cleared the requirements of the form.
If someone could provide a clear and concise example, it would much appreciated. I've tried to find a suitable example via google searching, however nothing seemed to fit. Also I'm trying to avoid using a validator plugin, which seemed to be the go to answer when googling the question.
I have my reasons and will be more than happy to explain if needed.
Thank-you,
Charles
if you take away the aspect of your question, validation is fairly basic. All jquery would be used for is to make selecting specific dom elements easier
$(function() {
$('form').submit(function() {
return checkFormIsValid();
});
$('#field1').keyup(function() {
checkField(this.id);
});
$('#field2').keyup(function() {
checkField(this.id);
});
});
function checkFormIsValid()
{
return checkField('field1') && checkField('field2');
}
function checkField(fieldId)
{
var val = $('#'+fieldId).val();
// validation logic
if(isValid) {
return true;
} else {
alert(fieldId+ ' is not valid');
return false;
}
}
This basic validation will be triggered on each field, as well as when the user submits the form.
As Ben Rowe suggest you can use that code, but in checkField(fieldId) function you have to validate that input data should be integer only in that case you can use these codes to vaildate that.
Regex to validet input data
var isEmail_re = /^\s*[\w\-\+_]+(\.[\w\-\+_]+)*\#[\w\-\+_]+\.[\w\-\+_]+(\.[\w\-\+_]+)*\s*$/;
function isEmail(s) {
return String(s).search(isEmail_re) != -1;
}
function isBlank(s) {
if (!s || s.length == 0) {
return true;
}
// checks for a non-white space character
// which I think [citation needed] is faster
// than removing all the whitespace and checking
// against an empty string
return !/[^\s]+/.test(s);
}
function SendContactForm() {
var isFormValid = true;
var isEmailOk = isEmail($('#cemail').val());
if (isEmailOk == false) {
$('#emEmail').css('color', 'red');
isFormValid = false;
}
else {
$('#emEmail').css('color', 'black');
}
var isNameOk = isBlank($('#cname').val());
if (isNameOk) {
$('#emName').css('color', 'red');
isFormValid = false;
//alert('!');
}
else {
$('#emName').css('color', 'black');
}
var isSubjectOk = isBlank($('#csubject').val());
if (isSubjectOk) {
$('#emSubject').css('color', 'red');
isFormValid = false;
}
else {
$('#emSubject').css('color', 'black');
}
var isMesageOk = isBlank($('#cmessage').val());
if (isMesageOk) {
$('#emMessage').css('color', 'red');
isFormValid = false;
}
else {
$('#emMessage').css('color', 'black');
}
if (isFormValid) {
$('#contactFormFields').hide("explode", 1000);
$.post("/Home/SendContactForm", { email: $('#cemail').val(),
name: $('#cname').val(),
subject: $('#csubject').val(),
message: $('#cmessage').val()
},
function (data) {
if (data.length > 0) {
// alert(data);
}
});
}
}
<div id="contactFormFields">
<table>
<tr>
<td style="width: 150px;">
E-Mail
</td>
<td>
<input id="cemail" type="text" value="E-mail" name="email" size="25" class="required email" /><em id="emEmail">*</em>
</td>
</tr>
<tr>
<td style="width: 150px;">
Name
</td>
<td>
<input id="cname" name="name" size="25" class="required" maxlength="100" /><em id="emName">*</em>
</td>
</tr>
<tr>
<td style="width: 150px;">
Subject
</td>
<td>
<input id="csubject" name="subject" size="25" class="required" maxlength="200" /><em id="emSubject">*</em>
</td>
</tr>
<tr>
<td style="width: 150px; vertical-align: top;">
Message
</td>
<td>
<textarea id="cmessage" maxlength="1000" name="comment" cols="27" rows="10" class="required"></textarea><em id="emMessage">*</em>
</td>
</tr>
<tr>
<td style="width: 150px;">
</td>
<td>
<input type="submit" value="Send" class="input-btn" onclick="SendContactForm();" style=" width:100px; color: Black;" />
</td>
</tr>
</table>
</div>
maybe your looking for a plug in to validate form fields?
you can give this a try: http://www.vanadiumjs.com/
just add its js file and your ready.
adding a required validation is as simple as adding css like this
<input class=":required" type="text">
to add an integer validation
<input class=":integer" type="text">
and so on. just follow the link for more info.

Categories

Resources