jQuery Wordpress Issue Form Validation - javascript

I have been through a series of revisions on this website I'm working on, basically, I need to add validation to email input field that only allows .edu extension for an only student type registrations.
Currently, there is a dropdown by which someone can select either student or a business. So when someone selects a student I want that validation rule to apply that only .edu can only register.
After struggling through google and StackOverflow I coded two scripts in jQuery which does not seem to be working well.
A user fills all the form fields and when at the select student the email input field should be checked and should stop the user to create an account if it does have .edu extension.
Code 1:
jQuery( document ).ready(function(){
jQuery('#reg_email').on('input',function(e){
var email = document.getElementById("reg_email");
var counter = 0;
if(jQuery(".chosen-single span").text().search("Student") == 0){
if (email.value.indexOf("#") != -1) {
if (!(/(.+)#(.+)\.(edu)$/.test(email.value))) {
if(counter<=0){
jQuery('#signup-dialog input[type="submit"]').prop('disabled', true);
jQuery(".form-row.form-row-wide:eq(1)").append('<p id="alert" style="padding-top:5px;color:red;">You are not eligible for an account. Please enter a valid .edu email.</p>');
counter++;
}
}else{
jQuery(#alert).remove();
jQuery('#signup-dialog input[type="submit"]').prop('disabled', false);
}
}
}
});
});
This Code above repeatedly adds the p tag but i tried to bound it to only once.
Code 2:
jQuery( document ).ready(function(){
var email = document.getElementById("reg_email");
if(jQuery(".chosen-single span").text().search("Student") == 0){
jQuery("#reg_email").validate({
rules: {
email: {
required: true,
email: true,
pattern: /(\.edu\.\w\w\w?)$/
}
}
});
}
});
This does not even work I have even included two scripts the validate.min.js and the additional-methods.min.js but still does not work.
It's like I'm starting to have a feeling that this is not even possible.
Please if someone can help it will be appreciated.
The website is website When you click signup you will see the sign-up modal box.
For now, I have removed all custom JS code. So you guys can check in the console.
P.S EDIT
Code 3: I tried even this
jQuery( document ).ready(function(){
var email = document.getElementById("reg_email");
var done = false;
jQuery(".chosen-single span").on('DOMSubtreeModified', function () {
if(jQuery(".chosen-single span").html() == 'Student') {
if (email.value.indexOf("#") != -1) {
if (!(/(.+)#(.+)\.(edu)$/.test(email.value))) {
if(!done) {
jQuery('#signup-dialog input[type="submit"]').prop('disabled', true);
jQuery(".form-row.form-row-wide:eq(1)").append('<p id="alert" style="padding-top:5px;color:red;">You are not eligible for an account. Please enter a valid .edu email.</p>');
done = true;
}
else{
jQuery("#alert").remove();
jQuery('#signup-dialog input[type="submit"]').prop('disabled', false);
}
}
}
});
});
But in this code, I only check domsubtreemodified and generate an alert box if the span value is 'Student' but the rest of the below code is not working.
This is the HTML FORM
<form method="post" class="register workscout_form">
<p class="form-row form-row-wide">
<label for="reg_username">Username <span class="required">*</span>
<i class="ln ln-icon-Male"></i>
<input type="text" class="input-text" name="username" id="reg_username" value="">
</label>
</p>
<p class="form-row form-row-wide">
<label for="reg_email">Email address <span class="required">*</span>
<i class="ln ln-icon-Mail"></i><input type="email" class="input-text" name="email" id="reg_email" value="">
</label>
</p>
<p class="form-row form-row-wide">
<label for="reg_password">Password <span class="required">*</span>
<i class="ln ln-icon-Lock-2"></i><input type="password" class="input-text" name="password" id="reg_password">
</label>
</p>
<p class="form-row terms wc-terms-and-conditions">
<label class="woocommerce-form__label woocommerce-form__label-for-checkbox checkbox">
<input type="checkbox" class="woocommerce-form__input woocommerce-form__input-checkbox input-checkbox" name="terms" id="terms" autocomplete="off"> <span>I’ve read and accept the terms & conditions</span> <span class="required">*</span>
</label>
<input type="hidden" name="terms-field" value="1">
</p>
<label for="user_email">I want to register as</label><select name="role" class="input chosen-select" style="display: none;"><option value="employer">Business</option><option value="candidate">Student</option></select><div class="chosen-container chosen-container-single chosen-container-single-nosearch" style="width: 100%;" title=""><a class="chosen-single" tabindex="-1"><span>Business</span><div><b></b></div></a><div class="chosen-drop"><div class="chosen-search"><input type="text" autocomplete="off" readonly=""></div><ul class="chosen-results"></ul></div></div>
<p class="form-row">
<input type="hidden" id="_wpnonce" name="_wpnonce" value="cc26c06e5b"><input type="hidden" name="_wp_http_referer" value="/"> <input type="submit" class="button" name="register" value="Register">
</p>
</form>
This is the last code 4 I'm using It kinda work nicely but just one thing is left is that when let suppose user corrects the email with a proper speciifed edu email the warning should go and the button should be enabled i can't get this to work in this way.
jQuery( document ).ready(function(){
var email = document.getElementById("reg_email");
var done = false;
jQuery("select[name='role']").change(function() {
if(jQuery("select[name='role']").children(':selected').html() == 'Student') {
if (email.value.indexOf("#") != -1) {
if (!(/(.+)#(.+)\.(edu)$/.test(email.value))) {
if(!done) {
jQuery('#signup-dialog input[type="submit"]').prop('disabled', true);
jQuery(".form-row.form-row-wide:eq(1)").append('<p id="alert" style="padding-top:5px;color:red;">You are not eligible for an account. Please enter a valid .edu email.</p>');
done = true;
}
else{
jQuery("#alert").remove();
jQuery('#signup-dialog input[type="submit"]').prop('disabled', false);
}
}
}
}
});
});

This should work, note that this will update on change, not after submitting the form.
function emailValid(email) {
var re = /(\.edu\.\w\w\w?)$/;
return re.test(email);
}
$(document).ready(function() {
$(document).on('change', '#reg_email', function() {
if ($(".chosen-single span").html() == 'Student') {
if (!emailValid($('#reg_email').val())) {
// Alert user that the email is not valid
}
else {
// Remove the alert
}
}
});
});

Okay so here is the complete code which helped me accomplish this task.
jQuery( document ).ready(function(){
var email = document.getElementById("reg_email");
var done = false;
jQuery("select[name='role']").change(function() {
if(jQuery("select[name='role']").children(':selected').html() == 'Student') {
if (email.value.indexOf("#") != -1) {
if (!(/(\.edu\.\w\w\w?)$/.test(email.value))) {
if(!done) {
jQuery('#signup-dialog input[type="submit"]').prop('disabled', true);
jQuery(".form-row.form-row-wide:eq(1)").append('<p id="alert" style="padding-top:5px;color:red;">You are not eligible for an account. Please enter a valid .edu email.</p>');
done = true;
}
else{
jQuery("#alert").remove();
jQuery('#signup-dialog input[type="submit"]').prop('disabled', false);
}
}
}
}if(jQuery("select[name='role']").children(':selected').html() == 'Business') {
done = false;
jQuery("#alert").remove();
jQuery('#signup-dialog input[type="submit"]').prop('disabled', false);
}
});
jQuery("#reg_email").on("change keyup paste", function(){
if(jQuery("select[name='role']").children(':selected').html() == 'Student') {
if (email.value.indexOf("#") != -1) {
if (/(\.edu\.\w\w\w?)$/.test(email.value)) {
jQuery("#alert").remove();
jQuery('#signup-dialog input[type="submit"]').prop('disabled', false);
}else{
if(jQuery("p#alert").length <= 1){
jQuery("p#alert").remove();
jQuery('#signup-dialog input[type="submit"]').prop('disabled', true);
jQuery(".form-row.form-row-wide:eq(1)").append('<p id="alert" style="padding-top:5px;color:red;">You are not eligible for an account. Please enter a valid .edu email.</p>');
done = true;
}
}
}
}
});
});
Everything is now working and it's awesome! It might help someone so though post this.

Related

Disabling jquery submit button until all the form inputs is filled

Disabling jquery submit button until all the form inputs is filled.
Am working with Jquery and I have been trying to implement disabling form submission button until the whole form inputs are filled. i have tried most solution found here but it does not solve the issue. Thanks
$('.postbtn_video').click(function() {
var element = $(this);
var ID = element.attr('id');
var msg = $('#status').val();
var title = $('#title').val();
var video = $('#video').val();
var stat = $('#stat').val();
if (title == "") {
alert('Please Enter video Post Title?');
} else if (msg == "") {
alert('Please Enter Video Post Description');
} else if (video == "") {
alert('Enter Youtube Video Link');
} else if (stat == "") {
alert('Select Status');
} else {
var postData = "post=" + msg + "&title=" + title + "&video=" + video + "&stat=" + stat;
$("#loader").show();
$("#loader").fadeIn(400).html('<img src="loader.gif" align="absmiddle"> <span class="loading">Loading Update...</span>');
$.ajax({
type: "POST",
url: "posts.php",
data: postData,
cache: false,
success: function(html) {
$("ul#updatepost").prepend(html);
$("ul#updatepost li:first").slideDown("slow");
$('#status').val('');
$('#loader').hide();
}
});
}
return false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="" method="post" name="statusform">
<label>Video Post Title </label>
<input type="text" name="title" id="title" class="form-control" placeholder="Enter Post Title">
<p></p>
<label>Video Post Description</label>
<textarea style="width:100%" name="status" class="status form-control" id="status" placeholder="Share what you like " title="What's on your mind?">
</textarea>
<label>Youtube Video Link</label>
<input style="width:100%" name="video" class="form-control" id="video" placeholder="Youtube Video Link">
<label>status</label>
<select style="width:100%" name="stat" class="form-control" id="stat">
<option value="ok">ok</option>
</select>
<p></p>
<input name="post" type="submit" value="Share Video Updates" class="postbtn_video" style="background:black;color:white; height:30px;float:left" />
</form>
Firstly apply disabled="disabled" to the button:
<input name="post" type="submit" value="Share Video Updates" class="postbtn_video" disabled="disabled" />
Secondly, you need a function which will check each field is empty or not!
Check below code:
$(document).ready(function(){
$('form > input').keyup(function() {
var empty = false;
$('form > input').each(function() {
if(!empty){ // this will only check next inputs if empty is false, but once its set to true no further check will be made
if ($(this).val() == '') {
empty = true;
}
}
});
if (empty) {
$('.postbtn_video').attr('disabled', 'disabled');
} else {
$('.postbtn_video').removeAttr('disabled');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="" method="post" name="statusform">
<label>Video Post Title </label>
<input type="text" name="title" id="title" class="form-control" placeholder="Enter Post Title">
<p></p>
<label>Video Post Description</label>
<textarea style="width:100%" name="status" class="status form-control" id="status" placeholder="Share what you like " title="What's on your mind?"></textarea>
<label>Youtube Video Link</label>
<input style="width:100%" name="video" class="form-control" id="video" placeholder="Youtube Video Link">
<label>status</label>
<select style="width:100%" name="stat" class="form-control" id="stat">
<option value="ok">ok</option>
</select>
<p></p>
<input name="post" type="submit" value="Share Video Updates" class="postbtn_video" disabled="disabled" />
</form>
Maybe this will help. you can manipulated the Form Disabled attribute:
var checkboxes = document.getElementsByTagName('input');
//check all check all input elements to see if they are check-boxes
for (var i = 0; i < checkboxes.length; i++) {
//If the input is a check-box run script else skip over
if (checkboxes[i].type == 'checkbox') {
//If it is a check-box ensure the box is unchecked
checkboxes[i].checked = false;
}
}
$(document).ready(function()
{
//define Element by ID and create variable
var $checked = $('#field_human');
//define default state for attribute before handler function trigger
$("#submit").attr("disabled", !$checked.checked)
//On element handler trigger define function to execute each time handler is triggered
$checked.click(function()
{
//State to define instance on method
if ($checked.prop('checked'))
{
//return true
//remove element attribute state 'disabled'
$('#submit').removeAttr('disabled');
}
if($('#contactForm input').val() != '')
{
$('#submit').removeAttr('disabled');
}
else {
//return false
//set element attribute state 'disabled'
$("#submit").attr("disabled", !$checked.checked);
}
//return to ready-state to wait for handler to trigger again
return;
});
});
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.0/umd/popper.min.js"></script>
<form class="form-horizontal" role="form" method="post" action="" id="contactForm" name="contactForm">
<div class="form-group">
<label for="inputblk" class="col-sm-3 control-label">Input Block</label>
<div class="col-sm-9">
<input name="inputblk" class="form-control" />
</div>
</div>
<div class="form-group">
<label for="human" class="col-sm-3 control-label">Are You <strong><u>Human</u>?</strong></label>
<div class="col-sm-9">
<input id="field_human" class="field_human" type="checkbox" name="human" />
</div>
</div>
<div class="form-group">
<div class="col-sm-9 col-sm-offset-3">
<button id="submit" name="submit" type="submit" class="btn btn-dark btn-block btn-lg">Send</button>
</div>
</div>
</form>
1st:
inputs that you think are required, make it required! like below:
<input style="width:100%" name="video" class="form-control" id="video" placeholder="Youtube Video Link" required >
2nd:
Make your selection based on this attribute and check if values of these inputs are not empty. Disable the submit button if so.
3rd:
Make event listener to all inputs that have required attribute to listen user inputs.
something like this:
var l = $("[required='']");
function enableSubmit(l) {
if (l.length == 0) {
$("[name=post]").removeAttr('disabled');
} else {
for (var m = 0; m < l.length; m++) {
if (l[m].value.length == 0) {
$("[name=post]").attr("disabled", "disabled");
return;
}
}
$("[name=post]").removeAttr('disabled');
}
}
for (var m = 0; m < l.length; m++) {
l[m].addEventListener('input', function () {
enableSubmit(l);
});
}
First of all you need to add a disabled property to you input button by default like:
<input disabled name="post" type="submit" value="Share Video Updates" class="postbtn_video" style="background:black;color:white; height:30px;float:left" />
then in your jquery you need fire up a validate function that will check for all the inputs and if they are not empty you can simply remove the disabled property from your input button like:
$(document).on('keyup', "input:not([type='submit']", function () {
//set it to true by default
var valid = true;
//getting all the inputs except input submit
var inputTextboxes = $("input:not([type='submit'])");
inputTextboxes.each(function(e) {
//it enters this only if the valid is true for any one value, if valid is set to false at any point it won't check it for next inputs - works for first time
if (valid != false){
if ($(this).val()) {
valid = true;
}else{
valid = false;
}
}
else{
break; //breaks the loop
}
});
if (valid) {
$("input[type=submit]").prop("disabled", false);
} else {
$("input[type=submit]").prop("disabled", true);
}
}
Hope this helps

form validation problems with jquery / javascript

This is my first real project which involves form validation. I am experiancing a problem which I can not find the solution to.
The objective is this, there is a continue button which will be activated once all the field inputs have been passed as valid. I am going about this by creating seperate variables, all initially set as false, devoted to checking each input field. When the user has entered correct validation data, the variable is set to true.
I then run an if statement to check if all the variables are set to true, and if so, I activate the continue button which, when clicked, slides the next part of the form into the page.
HTML:
<div class="container">
<h3>Step 3: Your Details</h3>
<!-- SLIDE-IN DIV TO REPRESENT DAY PASS -->
<div class="row chosenmembership">
<div class="col-md-12 text-center" id="yourdetails">
<form action="" method="">
<div class="form-group">
<label for="email">Email:</label>
<input type="text" placeholder="Email Address" id="email" class="form-control your-details">
<span class="warning" id="email-warning"></span>
</div>
<div class="form-group">
<label for="name">Name:</label>
<input type="text" placeholder="Full Name" id="name" class="form-control your-details">
<span class="warning" id="name-warning"></span>
</div>
<div class="form-group">
<label for="number">Contact Number:</label>
<input type="text" placeholder="Contact Number" id="number" class="form-control your-details">
<span class="warning" id="number-warning"></span>
</div>
<div class="form-group">
<label for="dob">Date of Birth:</label>
<input type="date" id="dob" class="form-control your-details">
<span class="warning" id="dob-warning"></span>
</div>
</form>
<input type="submit" id="submit" value="CONTINUE">
</div>
</div>
</div>
JAVASCRIPT / JQUERY:
//collection of input form fields//
var formSubmit = $("#submit");
var emailField = $("#email");
var nameField = $("#name");
var numberField = $("#number");
//Switch to true when each validation has passed//
emailValidated = false;
nameValidated = false;
numberValidated = false;
//email validation check//
emailField.on("input",function(){
var emailInput = $(this).val()
var testExp = new RegExp(/[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,3}$/);
if (emailInput < 1) {
$("#email-warning").html("Email is required!");
$("#email-warning").css("visibility","visible");
emailValidated = false;
}
else if (!testExp.test(emailInput)){
$("#email-warning").html("Please enter a valid email");
$("#email-warning").css("visibility","visible");
emailValidated = false;
} else {
$("#email-warning").css("visibility","hidden");
emailValidated = true;
}
})
//name validation check//
nameField.on("input",function(){
var nameInput = $(this).val()
if (nameInput < 1) {
$("#name-warning").html("Name is required");
$("#name-warning").css("visibility","visible");
nameValidated = false;
} else {
$("#name-warning").css("visibility","hidden");
nameValidated = true;
}
})
//contact number validation check//
numberField.on("input",function(){
var numberInput = $(this).val()
if (typeof numberInput !== "number" && numberInput.length < 9) {
$("#number-warning").html("Please enter a valid number");
$("#number-warning").css("visibility","visible");
numberValidated = false;
} else {
$("#number-warning").css("visibility","hidden");
numberValidated = true;
}
})
if (emailValidated && nameValidated && numberValidated){
alert("correct");
}
})
at the moment, I am simply using the alert prompt to test if it is working, but it fails.
As mentioned, this is my first real form validation. Any other tips or advice would be greatly appreciated. Thanks for the help in advance.
There were a couple things that I found from copying pasting your snippets of code. 1 there was an ending "})" without a beginning $(document).ready(function(){ ". 2 none of your ".on" statements had an ending semi colon.
Here is my javascript with a small change
$(document).ready(function () {
//collection of input form fields//
var formSubmit = $("#submit");
var emailField = $("#email");
var nameField = $("#name");
var numberField = $("#number");
//Switch to true when each validation has passed//
emailValidated = false;
nameValidated = false;
numberValidated = false;
//email validation check//
emailField.on("input", function () {
var emailInput = $(this).val()
var testExp = new RegExp(/[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,3}$/);
if (emailInput < 1) {
$("#email-warning").html("Email is required!");
$("#email-warning").css("visibility", "visible");
emailValidated = false;
}
else if (!testExp.test(emailInput)) {
$("#email-warning").html("Please enter a valid email");
$("#email-warning").css("visibility", "visible");
emailValidated = false;
} else {
$("#email-warning").css("visibility", "hidden");
emailValidated = true;
enableContinue();
}
});
//name validation check//
nameField.on("input", function () {
var nameInput = $(this).val()
if (nameInput < 1) {
$("#name-warning").html("Name is required");
$("#name-warning").css("visibility", "visible");
nameValidated = false;
} else {
$("#name-warning").css("visibility", "hidden");
nameValidated = true;
enableContinue();
}
});
//contact number validation check//
numberField.on("input", function () {
var numberInput = $(this).val()
if (typeof numberInput !== "number" && numberInput.length < 9) {
$("#number-warning").html("Please enter a valid number");
$("#number-warning").css("visibility", "visible");
numberValidated = false;
} else {
$("#number-warning").css("visibility", "hidden");
numberValidated = true;
enableContinue();
}
});
enableContinue = function () {
if (emailValidated && nameValidated && numberValidated) {
$('#submit').prop('disabled', false);
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<h3>Step 3: Your Details</h3>
<!-- SLIDE-IN DIV TO REPRESENT DAY PASS -->
<div class="row chosenmembership">
<div class="col-md-12 text-center" id="yourdetails">
<form action="" method="">
<div class="form-group">
<label for="email">Email:</label>
<input type="text" placeholder="Email Address" id="email" class="form-control your-details">
<span class="warning" id="email-warning"></span>
</div>
<div class="form-group">
<label for="name">Name:</label>
<input type="text" placeholder="Full Name" id="name" class="form-control your-details">
<span class="warning" id="name-warning"></span>
</div>
<div class="form-group">
<label for="number">Contact Number:</label>
<input type="text" placeholder="Contact Number" id="number" class="form-control your-details">
<span class="warning" id="number-warning"></span>
</div>
<div class="form-group">
<label for="dob">Date of Birth:</label>
<input type="date" id="dob" class="form-control your-details">
<span class="warning" id="dob-warning"></span>
</div>
</form>
<input type="submit" class="btn btn-primary" id="submit" disabled="disabled" value="CONTINUE">
</div>
</div>
</div>
Your form CONTINUE button becomes enables once all fields have a value. Note: I did not try to improve your javascript any, just made it work.
Right now you synchronically check validation variables at script, so they are all false. You have to asynchronically check them after form submit. Just add event listener to form submit to check variables like this:
document.getElementById('#form').addEventListener('submit', function(){
if (emailValidated && nameValidated && numberValidated){
alert("correct");
}
});
Don't forget to set id to your form.
You may be able to save a lot of work if you leverage some of the built in HTML5 form validation. https://developer.mozilla.org/en-US/docs/Learn/HTML/Forms/Form_validation
This simple example adds a new field every time you submit the form, as long as the existing fields are valid. You would need to test the state of the form to see if you should be adding another section or submitting.
$('form').on('submit', function() {
$(this).find('fieldset').append('<input type="text" required />');
return false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<fieldset>
<input type="text" required />
</fieldset>
<input type="submit" id="submit" value="continue" />
</form>

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.

how to work radio buttons into a nesting conditional

So I learning jQuery atm, and have to make a Loan calculator based on choices, as well as validate enteries, then output a result.
l wanted to make sure you guys knew what i was trying to do, so i have here a flow chart of what is supposed to happen:
http://i59.tinypic.com/8z02sh.jpg
that shows what is supposed to be happening. Problem is i dont know how to do this is Jquery. The radio button selector i found online (through another question on here) seems weird and i dont know how to use it. I could do this using javascript, but then i wouldn't be learning anything. So here's my code so far.
Also, im getting an error on line 14 of my JS (line 14 in JSfiddle), and i cant figure out what it is.
JSfiddle: http://jsfiddle.net/keup5vaw/1/
HTML:
<h1>Loan Calc</h1>
<form id="salaryForm" name="salaryForm2" method="Post" action="javascript:void(0)">
<label for="salary">Enter your annual salary</label>
<input type="text" name="salary" id="salary">
</form>
<form id="creditform" name="creditForm" method="Post" action="javascript:void(0)">
<p>Please select your Credit Score</p>
<p><input type="radio" name="radio" id="over1" value="0">
<label for="over1">Over 600</label></p>
<p><input checked type="radio" name="radio" id="under1" value="0">
<label for="under1">Under 600</label></p>
</form>
<p> How long have you worked at your current job? </p>
<input class="job" id="job1" name="job" type="radio" value="0">
<label for="job1">I have worked at my current job over 1 year.</label><br>
<br/>
<input checked class="job" id="job2" name="job" type="radio" value="0">
<label for="job2">I have worked at my current job less than 1 year.</label><br>
</form>
<input type="button" id="check" name="check" value="Check">
<div id="message"></div>
and JS -
$('#check').click(function () {
var salary;
var isValid = $('#salaryForm').validate().form();
// if validation passes, display a message
if (isValid) {
var salary = Number($('#salary').val());
if (salary < 40000) {
if ($('input[name=radio]:checked').length > 0) {
if ($('input[name=job1]:checked').length > 0) {
$('#message').html("Loan Approved.")
} else if {
$('#message').html("Loan Denied.")
} else if {
$('#message').html("Loan Denied.")
}
}
} else(salary >= 40000) {
if ($('input[name=radio]:checked').length > 0) {
if ($('input[name=job1]:checked').length > 0) {
$('#message').html("Loan Approved.")
} else if {
if ($('input[name=job1]:checked').length > 0) $('#message').html("Loan Approved.")
} else if {
$('#message').html("Loan Denied.")
}
}
}
});
// form validation
$('#salaryForm').validate({
rules: {
salary: {
required: true,
digits: true,
range: [1, 1000000]
}
}
});
As per usual, thank you ahead of time, you guys are awesome.
Edit: Updated after Mottie helped out (thank you!), Still not seeing what line 14 is doing wrong, but changed the else to else if, and used the tidy up.
If your having problems with the checking if a radio is checked you can use this its a lot cleaner than what you are currently using and is more intuitive.
if($("#id1").is(":checked")){
// do something
}else if($("#id2").is(":checked")){
// do something else
}
Hope this helps.
Formatting your javascript is really important to catch those type of syntax error for your self. As #Mottie said use some kind of javascript formatter to fix those issues.Tidy Up,
http://jsbeautifier.org/ are better place to start up with. Here is the correct code
$('#check').click(function()
{
var salary;
var isValid = $('#salaryForm').validate().form();
// if validation passes, display a message
if (isValid)
{
var salary = Number($('#salary').val());
if (salary < 40000)
{
if ($('input[name=radio]:checked').length > 0)
{
if ($('input[name=job1]:checked').length > 0)
{
$('#message').html("Loan Approved.")
}
else
{
$('#message').html("Loan Denied.")
}
}
else
{
$('#message').html("Loan Denied.")
}
}
else if (salary >= 40000)
{
if ($('input[name=radio]:checked').length > 0)
{
if ($('input[name=job1]:checked').length > 0)
{
$('#message').html("Loan Approved.")
}
else
{
if ($('input[name=job1]:checked').length > 0)
$('#message').html("Loan Approved.")
}
}else
{
$('#message').html("Loan Denied.")
}
}
}
});
// form validation
$('#salaryForm').validate(
{
rules:
{
salary:
{
required: true,
digits: true,
range: [1, 1000000]
}
}
});
modified your jquery
http://jsfiddle.net/cvynLaqf/
$('#check').click(function(){
var salary;
//var isValid = $('#salaryForm').validate().form();
var isValid = true;
// if validation passes, display a message
if (isValid){
var salary = Number($('#salary').val());
if (salary < 40000){
if ($('input[type=radio]:checked').length > 0){
if ($('input[value=over1]:checked').length > 0) {
//if over 600 do this
if ($('input[id=job1]:checked').length > 0)
$('#message').html("Loan Approved.");
else
$('#message').html("Loan Denied.");
}
else {
$('#message').html("Loan Denied.");}
}
else {
$('#message').html("Loan Denied.");
}
} else if( salary >= 40000){
if ($('input[type=radio]:checked').length > 0){
if ($('input[value=over1]:checked').length > 0) {
//over 600 do this
$('#message').html("Loan Approved.");}
else {
//under 600 do this
if ($('input[id=job1]:checked').length > 0)
$('#message').html("Loan Approved.");
else
$('#message').html("Loan Denied.");
}
}
else {
$('#message').html("Loan Denied.");}
}
}
});
// form validation
//$('#salaryForm').validate({
// rules: {
// salary: {
// required: true,
// digits: true,
// range: [1, 1000000]
// }
// }
//});
<h1>Loan Calc</h1>
<form id="salaryForm" name="salaryForm2" method="Post" action="javascript:void(0)">
<label for="salary">Enter your annual salary</label>
<input type="text" name="salary" id="salary">
</form>
<form id="creditform" name="creditForm" method="Post" action="javascript:void(0)">
<p>Please select your Credit Score</p>
<p><input type="radio" name="radio" id="over1" value="over1">
<label for="over1">Over 600</label></p>
<p><input checked type="radio" name="radio" id="under1" value="under1">
<label for="under1">Under 600</label></p>
</form>
<p> How long have you worked at your current job? </p>
<input class="job" id="job1" name="job" type="radio" value="0">
<label for="job1">I have worked at my current job over 1 year.</label><br>
<br/>
<input checked class="job" id="job2" name="job" type="radio" value="1">
<label for="job2">I have worked at my current job less than 1 year.</label><br>
</form>
<input type="button" id="check" name="check" value="Check">
<div id="message"></div>
i commented out your validation because im getting an error on my part
Despite an answer already being accepted, I figured I'd post an updated script since you're just beginning to learn jQuery to maybe help you improve further.
You're way over complicating the conditionals (if/else statements) for starters.
Break it down based on the behavior you would like to accomplish and word out the functionality the same way too.
Makes it a lot easier to read if you (or someone else) needs to look at it again in 6 months.
Has Good Credit?
Has Standing Job?
Is Loan Approved?
Has Good Salary?
Here's the rewritten functional fiddle.
http://jsfiddle.net/q3xpsLmL/
I also merged the individual forms to clean up a little. I changed the validation to HTML 5's required, type=number, min and max since the .validate() plugin was not in the fiddle.
Relying on HTML 5 and jQuery submit() event to validate the form.
Some more info on HTML 5 validation and pattern if you're interested:
http://www.w3.org/html/wg/drafts/html/master/forms.html#the-pattern-attribute
You can even style it using css :valid and :invalid pseudo-classes
I had trouble interpreting your logic for a applicant with a good salary. So I set it to approve if the person has a good salary and either good credit or a standing job.
If you have questions on it just add a comment.
HTML
<h1>Loan Calc</h1>
<form id="salaryForm" name="salaryForm2" method="Post" action="javascript:void(0);">
<label for="salary">Enter your annual salary</label>
<input id="salary" type="number" name="salary" min="0" max="1000000000" required>
<p>Please select your Credit Score</p>
<p>
<input type="radio" name="radio" id="over1" value="over1">
<label for="over1">Over 600</label>
</p>
<p>
<input checked type="radio" name="radio" id="under1" value="under1">
<label for="under1">Under 600</label>
</p>
<p>How long have you worked at your current job?</p>
<input class="job" id="job1" name="job" type="radio" value="0">
<label for="job1">I have worked at my current job over 1 year.</label>
<br>
<br/>
<input checked class="job" id="job2" name="job" type="radio" value="1">
<label for="job2">I have worked at my current job less than 1 year.</label>
<br>
<button type="submit" id="check" name="check">Check</button>
</form>
<div id="message"></div>
JavaScript
//use strict to ensure variables are defined and to prevent collisions
"use strict";
//define DOM elements so events do not need refind the element.
var salryForm = $('#salaryForm');
var salaryElement = $('#salary');
var messageElement = $('#message');
var radioButtons = $('input[type=radio]');
var goodCredit = radioButtons.filter('[name=radio][value=over1]');
var standingJob = radioButtons.filter('[name=job][value=0]');
var isLoanApproved = function(salary){
//always be pecimistic and decline unless all conditions are met
var result = false;
var hasGoodCredit = goodCredit.is(':checked');
var hasStandingJob = standingJob.is(':checked');
var hasGoodSalary = (salary >= 40000);
/*
* if applicant doesn't have a good salary
* they have to have good credit and standing job to be approved
*/
if (!hasGoodSalary && hasGoodCredit && hasStandingJob) {
result = true;
/**
* otherwise if applicant does have a good salary
* they only need to have either good credit or standing job to be approved
*/
} else if(hasGoodSalary && (hasGoodCredit || hasStandingJob)) {
result = true;
}
return result;
};
/**
* track on submit rather than click so you can catch "<enter>" key presses as well
*/
salryForm.submit(function(e) {
var salary = salaryElement.val();
messageElement.html('Loan ' + (isLoanApproved(salary) ? 'Approved' : 'Denied'));
return false;
});

radio button make condition for given by validation

Process: first line "would you like to add you children" If "Yes" then check Textbox validation if "No" then continue to Submit form. See bellow image
Problem: Validation work but when select "No" then also validation checking in backend and disable submit button automatically.
Button code
<form>
<div class="main-fre">
<label>Would you like to add your Child(ren) now?</label>
<input style="margin-left: 10px;" class="main-fre" type="radio" name="child" value="yes" />Yes
<input class="" type="radio" name="child" value="no" />No
</div>
<div class="childform">
<div class="cls-input">
<label>First name:</label>
<input id="first_name" type="text" name="fname" value="" required="required" /><span class="reg-error" id="first_name_alert" style="font-size: 13px;width: 60%;"></span><br /><br />
</div></div>
<div class="submit_file">
<a class="wpcf7-submit1" id="prev" href="javascript:void(0);">Previous</a>
<input class="wpcf7-submit1" id="submit_file" style="font-size: 15px;" type="submit" name="submit" value="Submit" />
</div>
</form>
JQuery Code
jQuery(document).ready(function(){
jQuery("input:radio").change(function(){
var $value = jQuery("form input[type='radio']:checked").val();
if($value === 'no')
{
jQuery(".childform").hide();
}
else
{
jQuery(".childform").show();
}
});
jQuery("input:radio").change();
jQuery("#submit_file").click(function(){
var $value = jQuery("form input[type='radio']:checked").val();
if($value === 'yes')
{
var $first_name = jQuery("input#first_name").val();
if($first_name == '')
{
jQuery('#confirmemailmsg').css('display','none');
document.getElementById("first_name_alert").innerHTML="Please enter first name."
return false;
}
}
});
});
Can you suggestion me.
Thank you.
As mentioned by MelanciaUK, when no is selected you must remove the required attribute to avoid validating the empty name input on submit.
jQuery(document).ready(function(){
jQuery("input:radio").change(function(){
var valueA = jQuery("form input[type='radio']:checked").val();
if(valueA === 'no'){
//remove required attribute from first_name input
$("#first_name").removeAttr("required");
jQuery(".childform").hide();
}else{
jQuery(".childform").show();
}
});
jQuery("input:radio").change();
jQuery("#submit_file").click(function(){
var valueA = jQuery("form input[type='radio']:checked").val();
if(valueA === 'yes'){
var first_name = jQuery("input#first_name").val();
if(first_name == ''){
jQuery('#confirmemailmsg').css('display','none');
document.getElementById("first_name_alert").innerHTML="Please enter firs name."
return false;
}
}
});
});
working in jsfiddle

Categories

Resources