form submit goes to wrong page in wordpress - javascript

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.

Related

return true from javascript then form continue to submit

i have php page and javascript, the page is contact us form and before submit button there is captcha when form submit it checks captcha if it validate return true else alert and create again captcha but it doesn't work when it return true after that nothing happen
<?php
$action=$_REQUEST['action'];
if ($action=="") /* display the contact form */
{
?>
<form action="" id="demo-form" onsubmit="validateCaptcha()" method="POST" enctype="multipart/form-data" >
<h3>Quick Contact</h3>
<h4>Contact us today, and get reply with in 24 hours!</h4>
<input type="hidden" name="action" value="submit">
<input placeholder="Your name" name="name" id="name" type="text" tabindex="1" required autofocus><br>
<input placeholder="Your Email Address" name="email" id="mail" type="email" tabindex="2" required><br>
<input placeholder="Subject" id="sub" name="subject" type="text" tabindex="3" required><br>
<input placeholder="Mobile Number" name="number" pattern="^((\+92)|(0092)|(0))-{0,1}\d{3}-{0,1}\d{7}$|^\d{11}$|^\d{4}-\d{7}$" id="contactInformation" type="tel" tabindex="4" oninvalid="this.setCustomValidity('Enter mobile number like: 03001234567')"
oninput="this.setCustomValidity('')" > <br>
<textarea placeholder="Type your Message Here...." tabindex="6" name="message" id="msg" tabindex="5" required></textarea><br>
<div id="captcha">
</div><input type="text" placeholder="Enter Captcha Code Here" id="cpatchaTextBox"/><br>
<input name="submit" type="submit" value="Submit" tabindex="7" id="contact-submit" data-submit="...Sending" /><br>
<button type="reset" name="reset" tabindex="8" id="contact-reset">Clear Form</button>
</form>
<?php
}
else /* send the submitted data */
{
$name=$_REQUEST['name'];
$email=$_REQUEST['email'];
$subject=$_REQUEST['subject'];
$number=$_REQUEST['number'];
$message=$_REQUEST['message'];
if (($name=="")||($email=="")||($subject=="")||($number=="")||($message==""))
{
echo "All fields are required, please fill the form again.";
}
else{
$from="From: $name<$email>\r\nReturn-path: $email";
$msg= "Name: ".$name."\nContact Number: ".$number."\n".$message ;
mail("xyz#gmail.com", $subject, $msg , $from);
echo '<script type="text/javascript">',
'alert("EMAIL SENT..!");',
'setTimeout(function(){',
' window.location.href = "thanks.php";',
' }, 50);',
'</script>'
;
}
}
?>
</div>
</section>
</div>
<br/>
</div>
</div>
</div>
// JavaScript Document
var code;
function createCaptcha() {
//clear the contents of captcha div first
document.getElementById('captcha').innerHTML = "";
var charsArray =
"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ#!#$%^&*";
var lengthOtp = 6;
var captcha = [];
for (var i = 0; i < lengthOtp; i++) {
//below code will not allow Repetition of Characters
var index = Math.floor(Math.random() * charsArray.length + 1); //get the next character from the array
if (captcha.indexOf(charsArray[index]) == -1)
captcha.push(charsArray[index]);
else i--;
}
var canv = document.createElement("canvas");
canv.id = "captcha";
canv.width = 100;
canv.height = 50;
var ctx = canv.getContext("2d");
ctx.font = "25px Georgia";
ctx.strokeText(captcha.join(""), 0, 30);
//storing captcha so that can validate you can save it somewhere else according to your specific requirements
code = captcha.join("");
document.getElementById("captcha").appendChild(canv); // adds the canvas to the body element
}
function validateCaptcha() {
event.preventDefault();
if (document.getElementById("cpatchaTextBox").value == code) {
return true;
}else{
alert("Invalid Captcha. try Again");
createCaptcha();
}
}
kindly if anyone can do that for me i just want, when captcha validate the form submit and email sent to the person.
There are multiple ways to handle this, one of the simpler solution is to cast event.preventDefault() only when needed.
No need to return anything.
function validateCaptcha() {
if (document.getElementById("cpatchaTextBox").value != code) {
event.preventDefault();
alert("Invalid Captcha. try Again");
createCaptcha();
}
}
WORKING DEMO CAPTCHA OK
function validateCaptcha() {
const captchaMock = false; // switch true/false to see the behavior
if (captchaMock) {
event.preventDefault();
alert("Invalid Captcha. try Again");
createCaptcha();
}
}
function createCaptcha() {
alert('New captcha');
}
<form action="http://www.google.com" onsubmit="validateCaptcha()">
<button>Submit</button>
</form>
WORKING DEMO CAPTCHA NOT OK
function validateCaptcha() {
const captchaMock = true; // switch true/false to see the behavior
if (captchaMock) {
event.preventDefault();
alert("Invalid Captcha. try Again");
createCaptcha();
}
}
function createCaptcha() {
alert('New captcha');
}
<form action="http://www.google.com" onsubmit="validateCaptcha()">
<button>Submit</button>
</form>
onsubmit="validateCaptcha()"
should be
onsubmit="return validateCaptcha()"
to prevent the return value of validateCaptcha being thrown away. In addition, validateCaptcha needs to return boolean false to prevent form submission - returning some other falsey value such as undefined doesn't work.
You can also pass the event object to the validation routine using
onsubmit="return validateCaptcha( event)"
which allows cancelling the event in the validation routine using event methods called on the event argument.
However, adding event handlers in HTML is error-prone, and adding submit event handlers to the form in JavaScript using
formObject.addEventListener("submit", submitHandler, true);
may be preferable - the submit handler gets called with event as its argument.

jQuery Wordpress Issue Form Validation

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.

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!

Force user to fill all fields before enabling form submit

I have a form containing various fields.
See jsFiddle demo.
My aim is to enable the submit button only when the user has filled in all fields.
So far, I'm able to force the title field to have content before submit button is enabled. How do I make it so that all other fields need to be filled too before submit button is enabled.
jQuery("input[type='text']").on("keyup", function () {
if (jQuery(this).val() != "" ) {
if (jQuery("#titlenewtide").val() != '')
{
jQuery("#subnewtide").removeAttr("disabled");
}
} else {
jQuery("#subnewtide").attr("disabled", "disabled");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="#" method="post" id="new_tide">
Title: <input id="titlenewtide" type="text" name="title" required> <br>
Description: <textarea name="description" id="description"></textarea> <br>
Tag: <input id="newtag" type="text" name="newtag" required> <br>
Category: <input type="radio" name="category" value="19" required> Animation
<button type="submit" value="Submit" name="subnewtide" id="subnewtide" disabled="disabled">Submit</button>
</form>
Note that I am loading the JavaScripts in my footer.
Make the changes take effect after changing inputs values:
On each input change, test the values of other inputs and checked state of radio, if all inputs has been entered it will make the submit button enabled:
var validateInputs = function validateInputs(inputs) {
var validForm = true;
inputs.each(function(index) {
var input = $(this);
if (!input.val() || (input.type === "radio" && !input.is(':checked'))) {
$("#subnewtide").attr("disabled", "disabled");
validForm = false;
}
});
return validForm;
}
inputs.change(function() {
if (validateInputs(inputs)) {
$("#subnewtide").removeAttr("disabled");
}
});
Demo:
var inputs = $("form#myForm input, form#myForm textarea");
var validateInputs = function validateInputs(inputs) {
var validForm = true;
inputs.each(function(index) {
var input = $(this);
if (!input.val() || (input.type === "radio" && !input.is(':checked'))) {
$("#subnewtide").attr("disabled", "disabled");
validForm = false;
}
});
return validForm;
}
inputs.change(function() {
if (validateInputs(inputs)) {
$("#subnewtide").removeAttr("disabled");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="#" method="post" id="myForm">
Title:
<input id="titlenewtide" type="text" name="title" required>
<br>Description:
<textarea name="description" id="description"></textarea>
<br>Tag:
<input id="newtag" type="text" name="newtag" required>
<br>Category:
<input type="radio" name="category" value="19" required>Animation
<button type="submit" value="Submit" name="subnewtide" id="subnewtide" disabled="disabled">Submit</button>
</form>
Also it uses the form id="myForm", so you can use it to validate only specific forms in your pages.
Note: This is tested and working on Chrome, Firefox and IE.
EDIT:
Make the changes take effect when we type in the inputs:
In the previous code we are using onchange event handler to call the function so it's only called when we click outside a given input (after change).
To perform the call automatically when the user enters a character in a field (the last one) we need to use the onkeyup event so we don't need to click outside of it.
This is the changed code you need :
var inputs = $("form#myForm input, form#myForm textarea");
var validateInputs = function validateInputs(inputs) {
var validForm = true;
inputs.each(function(index) {
var input = $(this);
if (!input.val() || (input.type === "radio" && !input.is(':checked'))) {
$("#subnewtide").attr("disabled", "disabled");
validForm = false;
}
});
return validForm;
}
inputs.each(function() {
var input = $(this);
if (input.type === "radio") {
input.change(function() {
if (validateInputs(inputs)) {
$("#subnewtide").removeAttr("disabled");
}
});
} else {
input.keyup(function() {
if (validateInputs(inputs)) {
$("#subnewtide").removeAttr("disabled");
}
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="#" method="post" id="myForm">
Title:
<input id="titlenewtide" type="text" name="title" required>
<br>Description:
<textarea name="description" id="description"></textarea>
<br>Tag:
<input id="newtag" type="text" name="newtag" required>
<br>Category:
<input type="radio" name="category" value="19" required>Animation
<button type="submit" value="Submit" name="subnewtide" id="subnewtide" disabled="disabled">Submit</button>
</form>
Use this code below. On each input, it will check all the form fields by using this function validate().
jQuery("input[type='text'], textarea").on("input", function () {
var isValid = validate();
if (isValid) {
jQuery("#subnewtide").removeAttr("disabled");
} else {
jQuery("#subnewtide").attr("disabled", "disabled");
}
});
function validate() {
var isValid = true;
$('input, textarea').each(function() {
if ($(this).val() === '')
isValid = false;
});
return isValid;
}
Fiddle
Update
To make it validate if the form has id="new_tide" and fix about the radio button.
$("input[type='text'], textarea").on("change input", function() {
validate($(this));
});
$("input:radio[name='category']").on("change", function() {
validate($(this));
});
function validate(self) {
if (self.parents("form:first").attr("id") == "new_tide") {
var isValid = true;
$('input[type="text"], textarea').each(function() {
if ($(this).val() === '')
isValid = false;
});
if (!$("input:radio[name='category']").is(':checked'))
isValid = false;
if (isValid) {
$("#subnewtide").removeAttr("disabled");
} else {
$("#subnewtide").attr("disabled", "disabled");
}
}
}
Fiddle
Here's how you can do it:
$(document).ready(function () {
var $inputs = $("#new_tide input:not([type=hidden]), #new_tide textarea");
$inputs.on("input change", function () {
valid = true;
$inputs.each(function () {
valid *= this.type == "radio" ? this.checked : this.value != "";
return valid;
});
$("#subnewtide").prop("disabled", !valid);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<form action="#" method="post" id="new_tide">
Title: <input id="titlenewtide" type="text" name="title" required> <br>
Description: <textarea name="description" id="description"></textarea> <br>
Tag: <input id="newtag" type="text" name="newtag" required> <br>
Category: <input type="radio" name="category" value="19" required> Animation
Hidden: <input type="hidden">
<button type="submit" value="Submit" name="subnewtide" id="subnewtide" disabled="disabled">Submit</button>
</form>
Try utilizing .siblings() , .map() to compile values of form elements , Array.prototype.every() to return Boolean representation of input , textarea values , set disabled property of form input[type=submit] element
$("form *[required]").on("input change", function(e) {
$(this).siblings("[type=submit]").prop("disabled"
, !$(this).siblings(":not([type=submit])").add(this).map(function(_, el) {
return el.type === "radio" ? el.checked : el.value
}).get().every(Boolean)
);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<form action="#" method="post" id="new_tide">
Title: <input id="titlenewtide" type="text" name="title" required> <br>
Description: <textarea name="description" id="description" required></textarea> <br>
Tag: <input id="newtag" type="text" name="newtag" required> <br>
Category: <input type="radio" name="category" value="19" required> Animation
<button type="submit" value="Submit" name="subnewtide" id="subnewtide" disabled="disabled">Submit</button>
</form>
By far the easiest, would be to rely on the HTML5 validation you're already using.
You'd have to add required to all form controls if you want to require all of them, and that can easily be done by using jQuery's :input selector and setting the property, like so
$(':input:not(#subnewtide)').prop('required', true)
We'll exclude the submit button, as that doesn't have to be required, obviously, not that it would matter in this case.
Then we'll listen for the input event, which covers all sorts of inputs, like typing, pasting etc, and the change event as well to cover the radio button.
Using form.checkValidity() tells us if the form is valid, and returns a boolean, so we could use it directly to set the disabled property of the submit button.
All together it looks like this, and that's all you need, a few lines of really simple code
$(':input:not(#subnewtide)').prop('required', true).on('input change', function() {
$('#subnewtide').prop( 'disabled', !this.form.checkValidity() );
});
FIDDLE
If you have to support old browsers that don't have HTML5 validation, you can use the H5F polyfill
My solution is base on standard JavaScript.
HTML form
<form action="#" method="post" id="new_tide" name="form1">
Title: <input onkeyup="myBtnActivator(1)" id="titlenewtide" name="title" type="text" required> <br>
Description: <textarea onkeyup="myBtnActivator(2)" id="description" name="description"></textarea> <br>
Tag: <input id="newtag" onkeyup="myBtnActivator(3)" name="newtag" type="text" required> <br>
Category: <input name="category" onchange="myBtnActivator(4)" type="radio" value="19" required> Animation
<button id="subnewtide" name="subnewtide" type="submit" value="Submit">Submit</button>
</form>
JavaScript
<script>
document.getElementById("subnewtide").disabled = true;
var input1 = false;
var input2 = false;
var input3 = false;
var input4 = false;
function myBtnActivator(i) {
switch (i) {
case 1:
input1 = true;
if (document.form1.title.value == "")
input1 = false;
break;
case 2:
input2 = true;
if (document.form1.description.value == "")
input2 = false;
break;
case 3:
input3 = true;
if (document.form1.newtag.value == "")
input3 = false;
break;
case 4:
input4 = true;
if (document.form1.subnewtide.value == "")
input4 = false;
break;
}
trigger();
}
function trigger() {
if (input1 == true && input2 == true && input3 == true && input4 == true) {
document.getElementById("subnewtide").disabled = false;
} else {
document.getElementById("subnewtide").disabled = true;
}
}
</script>
Why don't you use jquery validate . It's a good plugin .
The logic works like, any change in the form it will check the form is valid or not. And also using the errorplacement function it will disable the default error message also.
$().ready(function() {
// validate signup form on keyup and submit
$("#contactForm").validate({
rules: {
title: "required",
description: {
required: true
},
newtag: {
required: true
},
category: {
required: true
}
},
errorPlacement: function(error, element) {
return true;
},
submitHandler: function() {
}
});
$('#contactForm').change(function() {
if ($("#contactForm").valid()) {
$("#subnewtide").removeAttr("disabled");
}
});
});
Fiddle
There's actually a pretty easy approach. I'm using native JavaScript, but I think it is applicable in jQuery as well:
var form = document.getElementById("new_tide");
form.onchange = function onChange() {
var enable = true;
var inputs = form.getElementsByTagName("input");
var textareas = form.getElementsByTagName("textarea");
for (var i in inputs) {
enable = enable && inputs[i].value != "";
}
for (var i in textareas) {
enable = enable && textareas[i].value != "";
}
enable = enable && textarea.value != "";
document.getElementById("subnewtide").disabled = !enable;
}
The change event on form is always called, when any input or textarea element was changed (click in element, type, click somewhere else or lose focus).
Edit:
Regarding hidden fields, you can exclude them by surrounding the enable calculation with an if-condition:
if (!inputs[i].hidden) {
enable = enable && inputs[i].value != "";
}
Note:
This will work in any browser (even Internet Explorer 5.5). Check on MDN:
for ..in Loop
element.getElementsByTagName()
document.getElementById()
Thought I might chip in. Assuming as little as possible.
jQuery("input, textarea").on("keyup click", function () { // going vanilla after easy-mode attach
var sub = document.getElementById('subnewtide');
if (require_all(find_form(this))) {
sub.removeAttribute('disabled');
sub.disabled = false;
} else {
sub.setAttribute('disabled', 'disabled');
sub.disabled = true;
}
});
function concat(a, b) { // concating Array-likes produces Array
var slice = [].slice; // not assuming Array.prototype access
return [].concat.call(
slice.call(a, 0),
slice.call(b, 0)
);
}
function find_form(e) { // shim input.form
if (e) do {
if (e.tagName === 'FORM') return e;
} while (e = e.parentNode);
return null;
}
function require_all(form, dontIgnoreHidden) { // looks at textareas & inputs (excluding buttons)
var inp = concat(form.getElementsByTagName('input'), form.getElementsByTagName('textarea')),
rad = {}, // not assuming Object.create
i, j,
has = {}.hasOwnProperty; // not assuming Object.prototype access
for (i = 0; i < inp.length; ++i) {
switch ((inp[i].type || '').toLowerCase()) {
default: // treat unknown like texts
case 'text':
if (!inp[i].value) return false; break;
case 'checkbox':
if (!inp[i].checked) return false; break;
case 'radio':
j = inp[i].getAttribute('name');
if (!rad[j]) rad[j] = inp[i].checked;
break;
case 'hidden':
if (dontIgnoreHidden && !inp[i].value) return false; break;
case 'button':
case 'submit':
break;
}
}
for (j in rad) if (!has || has.call(rad, j)) // not assuming hasOwnProperty
if (!rad[j]) return false;
return true;
}
Here is a quick way to accomplish that. It involves attaching a change event listener to :radio and :checkbox elements and an input event listener to other elements. These can both use a common predefined handler that will count the number of unfilled element each time each of these events fires on the appropriate element.
function checkForm() {
//define and initialize variables
var unfilled = 0,
form = $(this.form);
//disable submit button if enabled
$(':submit', form).prop('disabled', true);
//count number of unfilled elements
$(':input', form).each(function() {
if( $(this).is(':radio,:checkbox') ) {
$('input[name=' + this.name + ']:checked').length || unfilled++;
} else {
$('[name=' + this.name + ']').val() || unfilled++;
}
});
//enable submit button if no unfilled element is found
unfilled || $(':submit', form).prop('disabled', false);
}
//set up event listeners to fire above handler
$(':text,textarea,select').on('input', checkForm);
$(':radio,:checkbox').on('change', checkForm);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form action="#" method="post" id="new_tide">
Title: <input id="titlenewtide" type="text" name="title" required> <br>
Description: <textarea name="description" id="description"></textarea> <br>
Tag: <input id="newtag" type="text" name="newtag" required> <br>
Category: <input type="radio" name="category" value="19" required> Animation
<button type="submit" value="Submit" name="subnewtide" id="subnewtide" disabled="disabled">Submit</button>
</form>
var inputs = $("form#myForm input, form#myForm textarea");
var validateInputs = function validateInputs(inputs) {
var validForm = true;
inputs.each(function(index) {
var input = $(this);
if (!input.val() || (input.type === "radio" && !input.is(':checked'))) {
$("#subnewtide").attr("disabled", "disabled");
validForm = false;
}
});
return validForm;
}
inputs.each(function() {
var input = $(this);
if (input.type === "radio") {
input.change(function() {
if (validateInputs(inputs)) {
$("#subnewtide").removeAttr("disabled");
}
});
} else {
input.keyup(function() {
if (validateInputs(inputs)) {
$("#subnewtide").removeAttr("disabled");
}
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="#" method="post" id="myForm">
Title:
<input id="titlenewtide" type="text" name="title" required>
<br>Description:
<textarea name="description" id="description"></textarea>
<br>Tag:
<input id="newtag" type="text" name="newtag" required>
<br>Category:
<input type="radio" name="category" value="19" required>Animation
<button type="submit" value="Submit" name="subnewtide" id="subnewtide" disabled="disabled">Submit</button>
</form>
Use this html<br>
HTML:
<br>
<pre>
<form action="#" method="post" id="">
Title: ##<input id="titlenewtide" type="text" name="title" required>
Description: <textarea name="description" id="description"></textarea>
Tag: <input id="newtag" type="text" name="newtag" required>
Category: <input type="checkbox" onclick="validate()" name="category" id="cate"value="19" required > Animation
<button type="submit" value="Submit" name="subnewtide" id="subnewtide" disabled="disabled">Submit</button>
</form>
</pre>
validation code:<br>
//on each key up function intiate the function validate
<pre>
jQuery("input[type='text']").on("keyup", function () {
validate();
});
jQuery("#description").on("keyup", function () {
validate();
});
function validate(){
jQuery("input[type='text']").each(function(){
if (jQuery(this).val() != "" )
{
if((jQuery("#description").val() !="") && (jQuery("#cate").is(':checked')))
{
jQuery("#subnewtide").removeAttr("disabled");
}
else {
jQuery("#subnewtide").attr("disabled", "disabled");
}
}
});
}
</pre>
you can find the fiddle in : https://jsfiddle.net/s8uv2gkp/
Maytham Fahmi's relatively easy solution can be made even easier by passing this.name.
<form action="#" method="post" id="new_tide" name="form1">
<input onkeyup="myBtnActivator(this.name)" name="title" type="text" required> <br>
<textarea onkeyup="myBtnActivator(this.name)" name="description"></textarea> <br>
<input id="newtag" onkeyup="myBtnActivator(this.name)" name="newtag" type="text" required> <br>
<input name="category" onchange="myBtnActivator(this.name)" type="radio" value="19" required> Animation
<button id="subnewtide" name="subnewtide" type="submit" value="Submit">Submit</button>
</form>
this refers to the DOM object that called the function. So the switch can just directly take the name, or the value, or anything else you can pass with DOM.
myBtnActivator(n)
{
switch(n)
{
case "title":
break;
case "description":
break;
case "newtag":
break;
case "category":
break;
}
}

Stopping action if requirements are not met

I want to check the validation of two text boxs if either one is empty. It showed show an error as an innerHTML and if they are both filled in. It will then continue to action. Here is my code:
function go()
{
var toCheck = document.getElementById('myAnchor');
if (toCheck != '') {
return true;
}
else
{
document.getElementById('myAnchor').innerHTML = 'Fred Flinstone';
}
}
this does set the innerHTML but still continues with the action. How can I stop it from continuing?
Thank you!
You should check the value of text box,
Change the code to
function go()
{
var toCheck = document.getElementById('myAnchor').value;
if (toCheck != '') {
return true;
}
else
{
document.getElementById('myAnchor').innerHTML = 'Fred Flinstone';
}
}
add the onsubmit on the form:
<form onsubmit="return true;">
...
</form>
if the return is false it will stop from submitting an opposite scenario if it's true. you could also call your functions on that attribute and do the same thing then if it doesn't fit the condition it will stop from submitting your form and do the other process you desire to happen.
Textfields use the value attribute.
document.getElementById('myAnchor').value = 'Fred Flinstone';
An empty textfield would have a value of "".
function go()
{
var toCheck = document.getElementById('myAnchor');
if (toCheck.value != "") {
return true;
}
else
{
toCheck.value = 'Fred Flinstone';
}
}
Here's a working example.
<!DOCTYPE html>
<html>
<body>
<form name="form" action="data.php">
<label style="float:left">
<font face="Comic Sans MS">* username &nbsp
</label></font>
<input type="text" id='textfield' name="name" size="40" style="float: left;">
<label id='myAnchor' style="display: inline; padding-left: 20px;"></label> <br/> <br/>
<label style="float:left"><font face="Comic Sans MS">* password &nbsp</label></font>
<input type="text" name="pwd" size="40" style="float: left;">
<label id="myAnchor2" style="display: inline; padding-left: 20px;">
</label> <br/> </p> <input type="button" value="LogIn" onClick="return go();"> </form>
</body>
<script>
function go()
{
var toCheck = document.getElementById('textfield');
if (toCheck.value != "") {
return true;
}
else
{
toCheck.value = 'Fred Flinstone';
}
}
</script>
</html>
In your question you said that
I want to check the validation of two text boxs
In that case you should be checking the value of textboxes, not the myAnchor.
I would change your html code like this:
<input type="text" name="name" id="name" size="40" style="float: left;">
<input type="text" name="pwd" id="pwd" size="40" style="float: left;">
<input type="submit" value="LogIn" onSubmit="go();">
adding id to the input boxes
then change the onClick event to onSubmit. that way you can perform javascript validation in the function, then submit the form if all goes well, otherwise display the error.
Then your script will be like...
function go() {
var name = document.getElementById('name').value,
pwd = document.getElementById('pwd').value;
if (name != '' && pwd != '') {
document.forms["form"].submit();
}
else {
document.getElementById('myAnchor').innerHTML = 'Fred Flinstone';
}
}

Categories

Resources