Show hide div and script based on radio button - javascript

I'm trying to implement validation into my form being conditional. Basically if the user selects email radio option then email is going to be required, or if phone is selected then phone field would be required.
So far I've gotten this code to work, form submits and validation works fine. But if I switch to phone, then switch back to email, the validation is loaded so form won't submit if I haven't filled out both fields.
I have it set that way but basically trying to make it so if one field is selected then the other required. Any better ways to do this?
HTML:
<label>Method of Contact</label>
<label class="radio">
<input type="radio" name="group" value="ck1" checked/>
Email
</label><br />
<label class="radio"><input type="radio" name="group" value="ck2" />
Phone
</label>
<div id="emaildisp">
<label>Email</label>
<input id="emailv" name="email" type="email" />
</div>
<div id="phonedisp">
<label>Phone</label>
<input id="phonev" name="phone" type="text" />
</div>
Javascript:
$(function()
{
if (jQuery('input[value=ck2]:checked').length > 0)
{
jQuery('#phonedisp').show();
jQuery('#emaildisp').hide();
jQuery("#phonev").validate(
{
expression: "if (VAL) return true; else return false;",
message: "Please enter your phone number"
});
}
else
{
jQuery('#phonedisp').hide();
jQuery('#emaildisp').show();
jQuery("#emailv").validate(
{
expression: "if (VAL) return true; else return false;",
message: "Please enter your email"
});
}
jQuery('input[name=group]').change(function()
{
var selected = jQuery(this).val();console.log(selected);
if(selected == 'ck2')
{
jQuery('#phonedisp').show();
jQuery('#emaildisp').hide();
jQuery("#phonev").validate(
{
expression: "if (VAL) return true; else return false;",
message: "Please enter your phone number"
});
}
else
{
jQuery('#phonedisp').hide();
jQuery('#emaildisp').show();
jQuery("#emailv").validate(
{
expression: "if (VAL) return true; else return false;",
message: "Please enter your email"
});
}
});
});
Solution:
Thanks to the answers below, I came up with the solution. Key difference, I was not using jquery validation plugin, rather a different validation script. So I switched over, for beginners, just look it up you'll simply have to add link to the script in the header.
Next I gave the form an id, #myform. Then I have the ck1 and ck2 radio button their own respective ids, #ck1id and #ck2id. And using the below code, if the radio button is selected, then depending on the id selected, next part becomes validation required.
<script type='text/javascript'>
$(function(){
jQuery('input[name=group]').change(function() {
var selected = jQuery(this).val();console.log(selected);
if(selected == 'ck2'){
jQuery('#phonedisp').show();
jQuery('#emaildisp').hide();
} else {
jQuery('#phonedisp').hide();
jQuery('#emaildisp').show();
}
});
jQuery('input[name=group]').triggerHandler('change');
});
</script>
<script>
$(function(){
// validate signup form on keyup and submit
$("#myform").validate({
rules: {
group: "required",
email:
{
required: '#ck1id:checked',
email: true
},
phone:
{
required: '#ck2id:checked',
digits: true
}
},
messages: {
group: "Please select one",
email: "Please enter your email.",
phone: "Please enter your phone."
}
});
});
</script>

You need to remove the previously added validation from the other fields those are not required. If you need phone remove validation from email and vice versa.
You can follow two way, either remove validation or ignore the validation.
1. Removing the validation:
jQuery("#emailv").rules('remove');
or
jQuery("#phonev").rules('remove');
2. Ignore validation:
jQuery("#emailv").validate({
ignore: "#emailv"
});
or
jQuery("#phonev").validate({
ignore: "#phonev"
});
Check if this helps you.

Use .rules("remove") to remove jquery validation.
$(function(){
jQuery('input[name=group]').change(function() {
var selected = jQuery(this).val();console.log(selected);
if(selected == 'ck2'){
jQuery('#phonedisp').show();
jQuery('#emaildisp').hide();
jQuery("#emailv").rules("remove"); //remove the other field validation
jQuery("#phonev").validate({
expression: "if (VAL) return true; else return false;",
message: "Please enter your phone number"
});
} else {
jQuery('#phonedisp').hide();
jQuery('#emaildisp').show();
jQuery("#phonev").rules("remove"); //remove the other field validation
jQuery("#emailv").validate({
expression: "if (VAL) return true; else return false;",
message: "Please enter your email"
});
}
});
jQuery('input[name=group]').triggerHandler("change");
});
I see that you have duplicated code, just remove it and use jQuery('input[name=group]').triggerHandler("change"); to trigger it when page first loads

Related

Trying to validate form field with jQuery

I know I must be missing something super simple here, because in theory this code is supposed to work, but it's not, and I cannot understand why. I'm trying to work out my own jQuery form validation, because I tried the jQuery form validator plug-in, and while setting up the rules and messages is perfectly simple, figuring out how to get the error message to show up where I wanted it to was a nightmare (couldn't get the message to show up AFTER radio buttons, for example.)
I've got the 1st part of my attempted validation working, but I can't clear the message once you enter something in the field. Also, the message pops up even when conditions are met, which doesn't make sense to me.
here's the jsfiddle
html
<form>
<p>
<lable for="name">Enter your name:</lable>
<input type="text" id="name" name="name">
<span class="error"></span>
</p>
<lable for="age">Enter your Age:</lable>
<input type="text" id="age" name="age" width="3">
<span class="error"></span>
</p>
</form>
jQuery
$("input").focusin(function(){//highlight input field on focus
$(this).css("background-color", "yellow");
});
$("input").focusout(function(){
$(this).css("background-color", "white");
});
$("#name").keyup(function(){ //check against non-letter characters in name field
var notLetter = /[^A-Za-z]/;
if (notLetter.test($(this))){
$(this).next(".error").text("Letters only please!");
} else {
$(this).next(".error").text("");
}
});
$("#name").focusout(function(){//check that the field isn't empty
if ($(this).val() == ""){
$(this).next(".error").text("You forgot to enter your name!");
} else {
$(this).next(".error").text("");
}
});
$("#age").keyup(function(){//check against non-number characters in age
var notNumber = /[^0-9]/;
if (notNumber.test($(this)) != false){
$(this).next(".error").text("Numbers only please!");
} else {
$(this).next(".error").text("");
}
});
$("#age").focusout(function(){//check that the field isn't empty
if ($(this).val() == ""){
$(this).next(".error").text("You forgot to enter your name!");
} else {
$(this).next(".error").text("");
}
});
You forgot the $(this).val()
$("#name").keyup(function(){ //check against non-letter characters in name field
var notLetter = /[^A-Za-z]/;
if (notLetter.test($(this).val())){
$(this).next(".error").text("Letters only please!");
} else {
$(this).next(".error").text("");
}
});
and again at age
$("#age").keyup(function(){//check against non-number characters in age
var notNumber = /[^0-9]/;
if (notNumber.test($(this).val())){
$(this).next(".error").text("Numbers only please!");
} else {
$(this).next(".error").text("");
}
});
also you can remove != false - e.g
if (test != false)
is the same as
if (test)
Heres the fixed up fiddle
Need to Remember Some thing while validating form Using JS:-
Check input value Using (this).val();
if Error Occur then forward to next vale with Error .
Check test value is false or true using if (test != false) or if (test)
then forward your Control for success page
You can use the lettersonly rule.
Here's an example:
Define a variable validator and do this :
validator = $("form").validate({
rules: {
name: { required: true,
lettersonly: true
}
}
});
It's worth noting, each additional method is independent, you can include that specific one, just place this before your .validate() call:
jQuery.validator.addMethod("lettersonly", function(value, element) {
return this.optional(element) || /^[a-z]+$/i.test(value);
}, "Letters only please");
you need to call
$("form").valid()
and if it is valid means without any errors then do :
validator.hideErrors();
$("form" div.has-error").removeClass("has-error");
For age input for numeric only jQuery has implemented its own jQuery.isNumeric() added in v1.7. See: https://stackoverflow.com/a/20186188/66767

Using jQuery to prevent form submission when input fields are empty

The solution should be pretty straightforward. I'm trying to prevent the form from submitting properly when no value is found within the input boxes. Here's my JSFiddle: http://jsfiddle.net/nArYa/7/
//Markup
<form action="" method="post" name="form" id="form">
<input type="text" placeholder="Your email*" name="email" id="email">
<input type="text" placeholder="Your name*" autocomplete=off name="name" id="user_name"
<button type="submit" id="signup" value="Sign me up!">Sign Up</button>
</form>
//jQuery
if ($.trim($("#email, #user_name").val()) === "") {
$('#form').submit(function(e) {
e.preventDefault();
alert('you did not fill out one of the fields');
})
}
As you can see in the JSFiddle, the problem is that when I type something into both fields, the alert box STILL pops up. I'm having a hard time figuring out why. Is there something wrong within my
if($.trim($"#email, #user_name").val()) === "") ?
Two things, #1 the check for empty fields should happen on every attempt of submit, #2 you need to check each field individually
$('#form').submit(function() {
if ($.trim($("#email").val()) === "" || $.trim($("#user_name").val()) === "") {
alert('you did not fill out one of the fields');
return false;
}
});
Updated fiddle
Your check occurs on page load. You need to check the field when the form is submitted.
$('#form').submit(function(e) {
if ($.trim($("#email, #user_name").val()) === "") {
e.preventDefault();
alert('you did not fill out one of the fields');
}
});
HTML5: use required in input tag
A boolean attribute.
Input field must be filled out before submitting the form.
Works with text, search, url, tel, email, password, date pickers, number, checkbox, radio, and file.
<input required type='text'...>
w3schools hint
I guess that this will help:
$('#form').submit(function(e) {
e.preventDefault();
$("#email, #user_name").each(function(){
if($.trim(this.value) == ""){
alert('you did not fill out one of the fields');
} else {
// Submit
}
})
})
Put your if statement inside the callback:
$('#form').submit(function(e) {
if ($.trim($("#email").val()) === "" || $.trim($("#user_name").val())) {
e.preventDefault();
alert('you did not fill out one of the fields');
//You can return false here as well
}
});

form validation error

I have little problem with form and I am using js for validation.
Here is my form code.
<form method="get" onkeydown="checkEnter()" action="emailform.php" id="signupform" name="subscribe">
<input name="email" id="email" type="text" value="Enter Email for Updates" onfocus="if(this.value=='Enter Email for Updates'){this.value=''};" />
<input type="hidden" name="submitted" id="submitted" value="true" />
</form>
id signupform I am using for validation and submit the form is on pressing enter button.
But there is problem when put signupform then my validation start working fine and when I enter correct email it's show me error and when I remove the signupform id then my form submission work fine without validation.
Here is my JS code for id signupform.
function SubscribeForm() {
$('#signupform').submit(function () {
$('.email').removeClass('error')
$('em.error').remove();
var error = false;
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if ($.trim($('.email').val()) == '') {
$(this).append('<em class="error">Please enter your email address.</em>');
$(this).addClass('error');
error = true;
} else if (!emailReg.test(jQuery.trim($('.email').val()))) {
$(this).append('<em class="error">Please enter a valid email address</em>');
$(this).addClass('error');
error = true;
}
if (!error) {
$("#submit", this).after('<span id="form_loading"></span>');
var formValues = $(this).serialize();
$.post($(this).attr('action'), formValues, function (data) {
$("#signupform").before(data);
});
$(':input[type="text"]').attr('value', '');
}
return false
});
}
change
return false
to
return error;
it is causing problem.
change
return false;
to
return !error;
Also, add css class "email" to input email field, or change jquery to selector code ".email" to "#email"
Also a possible solution, if you don't need to support the old browser: placeholder.
<input placeholder="Enter email" type="text"... />
Thanks for your help Guys. i just put this and now working fine.
$('#signupform').submit(function(){
$('.email').removeClass('error')
$('em.error').remove();
var filter = /^([\w-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
sEmail = document.getElementById('email').value;
if (filter.test(sEmail)) {
return true;
}
else {
if(sEmail == '')
{
$(this).append('<em class="error">Please enter your email address</em>');
$(this).addClass('error');
}
else
{
$(this).append('<em class="error">Please enter a valid email address</em>');
$(this).addClass('error');
}
return false;
}
});
});

jquery form validation using groups

I have an order form, one part of the form is the address. It contains Company, Street-Address, ZIP, Town, Country with a simple jquery form validation with every field required, and ZIP validated for number. Now what I want is to group them and only have one field showing "valid address" on success, or "address wrong" on error.
This is a part of my js code:
$("#pageform").validate(
{
messages: {
company_from: addressError, //addressError is a JS var for the error message
street_from: addressError,
zip_from: addressError,
town_from: addressError,
country_from: addressError
},
groups: {
from: "company_from street_from zip_from town_from country_from"
},
errorPlacement: function(error, element) {
if (element.attr("name") == "company_from"
|| element.attr("name") == "street_from"
|| element.attr("name") == "zip_from"
|| element.attr("name") == "town_from"
|| element.attr("name") == "country_from"
)
{
$("#error_from").append(error);
}
},
success: function(label) {
var attribute = $(label[0]).attr("for");
$(".err-ok-" + attribute + " .ok").css("display", "block").css("visibility", "visible");
}
}
);
This is a part of the corresponding HTML code:
<input type="text" name="company_from" id="company_from" class="required default input-s8" maxlength="255" />
<input type="text" name="street_from" id="street_from" class="required default input-s8" maxlength="255" />
<input type="text" name="zip_from" id="zip_from" class="required digits default input-s8" maxlength="5" onblur="checkCalculation()" />
<input type="text" name="town_from" id="town_from" class="required default input-s8" maxlength="255" />
<!-- and a select list for the country -->
You do not need to take a closer look on how I show the error and so on, my problem is, that I do not know when to show the error label and when the success label. When I enter a letter for the ZIP code, my errorPlacement function and the success function is called (and the errorPlacement first), so I guess it's always calling the success if there is at least one field correct.
Please ask if there are any questions, and I am pretty sure there are... :-)
Add rules
rules: {
company_from: "required",
company_from: "required",
zip_from: "required",
town_from:"required",
country_from:"required"
},

'success' dialog after jquery form validation clears and submits - showing success message no matter what

I have a simple email form:
<form method="post" action="process-form.php" id="emailForm" name="emailForm" target="_self">
<h4>Sign up to be notified when we go live!</h4>
<label for="email">E-mail</label>
<input type="text" name="email" id="email" />
<input type="submit" name="submit" id="submit" value="Submit" onclick="return alert('Thanks! Your email has been added.');">
<p>emails will not be shared with third parties</p>
</form>
I am using the following jQuery validation:
/*
Created 09/27/09
Questions/Comments: jorenrapini#gmail.com
COPYRIGHT NOTICE
Copyright 2009 Joren Rapini
*/
$(document).ready(function(){
// Place ID's of all required fields here.
required = ["email"];
// If using an ID other than #email or #error then replace it here
email = $("#email");
errornotice = $("#error");
// The text to show up within a field when it is incorrect
emptyerror = "Please fill out this field.";
emailerror = "Please enter a valid e-mail.";
$("#emailForm").submit(function(){
//Validate required fields
for (i=0;i<required.length;i++) {
var input = $('#'+required[i]);
if ((input.val() == "") || (input.val() == emptyerror)) {
input.addClass("needsfilled");
input.val(emptyerror);
errornotice.fadeIn(750);
} else {
input.removeClass("needsfilled");
}
}
// Validate the e-mail.
if (!/^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/.test(email.val())) {
email.addClass("needsfilled");
email.val(emailerror);
}
//if any inputs on the page have the class 'needsfilled' the form will not submit
if ($(":input").hasClass("needsfilled")) {
return false;
} else {
errornotice.hide();
return true;
}
});
// Clears any fields in the form when the user clicks on them
$(":input").focus(function(){
if ($(this).hasClass("needsfilled") ) {
$(this).val("");
$(this).removeClass("needsfilled");
}
});
});
After the form validates successfully I want a success dialog to display. I kind of have that going now with the onClick event for the submit button but obviously that is going to display the message no matter if it validates or not. I think the message needs to be placed in the validation somewhere.
At the end of your onsubmit function, where you return 'true'.

Categories

Resources