Better way to validate the form field combination with jQuery - javascript

I have a sample form with the following code (stripped for JSFiddle)
<input type="text" id="i1" />
<input type="text" id="i2" />
<input type="text" id="i3" />
<input type="text" id="e1"/>
<input type="text" id="e2" />
<input type="text" id="e3" />
<input type="button" id="submit" value="Submit">
The jQuery code follows (stripped for JSFiddle)
$("#e1").hide();
$("#e2").hide();
$("#e3").hide();
$("#submit").click(function(){
var a = $("#i1").val();
var b = $("#i2").val();
var c = $("#i3").val();
if (a == "" && b !== "" && c!=="") {
$("#e1").show();
} else if (a !== "" && b == "" && c=="") {
$("#e2").show();
$("#e3").show();
} else if (a !== "" && b !== "" && c=="") {
$("#e3").show();
}else if (a == "" && b == "" && c=="") {
$("#e1").show();
$("#e2").show();
$("#e3").show();
}
});
I am trying to validate the fields with possible combinations. It will show or hide the last three text fields (with id e*)accordingly if the fields are blank or not. For example, if the 1st field is empty and others are not, then e1 should be shown and others are hidden. Same of others like a typical form field were all fields are mandatory. If I write the above code, it is too long and complex. Is there any simple solution for this kind of scenario ?
Thanks

This will do what you want...
$(document).ready(function(){
$("#e1").hide();
$("#e2").hide();
$("#e3").hide();
$("#submit").click(function(){
$("input[id*=i]").each(function(i){
if($(this).val()=="") $("#e"+(i+1)).show();
else $("#e"+(i+1)).hide();
});
});
});

$(function(){
$("#e1").hide();
$("#e2").hide();
$("#e3").hide();
$("#submit").click(function(){
var a = $("#i1").val();
var b = $("#i2").val();
var c = $("#i3").val();
if (a == "") {
$("#e1").show();
}if (b == "") {
$("#e2").show();
}if (c == "") {
$("#e3").show();
}
});
})
<input type="text" id="i1" />
<input type="text" id="i2" />
<input type="text" id="i3" />
<input type="text" id="e1"/>
<input type="text" id="e2" />
<input type="text" id="e3" />
<input type="button" id="submit" value="Submit">
Demo

Related

Prevent submission of form for non numeric fields

I am trying to set up a form validation - this works - but only for odd numbers, if you enter an even number, e.g. part number TEST and quantity 2 then the alert will come up, if you enter qty 3 then the form will submit. Any ideas ?
Javascript
<script type="text/javascript">
function allnumeric(inputtxt)
{
var numbers = /^[0-9]+$/;
if(form2.qty.value.match(numbers) & (form2.product.value != ""))
{
return true;
}
else
{
alert('Please input numeric characters only or fill in the product field')
{
return false;
}
}
}
</script>
Form
<form id="form2" name="form2" method="post" action="booking-printlabel2.asp?insert=yes" onsubmit="return allnumeric()">
<input name="product" type="text" id="product" style="height:55px;font-size:30pt;" size="10"/>
<input name="qty" type="text" id="qty" style="height:55px;font-size:30pt;" size="3"/>
<input type="submit" name="Print Labels2" id="Print Labels2" value="Print Labels" style="height:55px;font-size:30pt;"/>
</form>
Thanks all - it was the typo, if(form2.qty.value.match(numbers) & (form2.product.value != "")) changed to if(form2.qty.value.match(numbers) && (form2.product.value != "")) and it now works.
Assuming you're targeting html5:
<input name="qty" type="number" id="qty" style="height:55px;font-size:30pt;"/>
Or if you really want to have type="text":
<input name="qty" type="text" id="qty" pattern="\d+" style="height:55px;font-size:30pt;"/>
Also, you've got a typo:
if(form2.qty.value.match(numbers) & (form2.product.value != ""))
should be
if(form2.qty.value.match(numbers) && (form2.product.value != ""))
Inside of your if condition you have to add one more if condition to check the odd and even number. You have to do this:
if(form2.qty.value.match(numbers) & (form2.product.value != ""))
{
var num = form2.qty.value;
if(num%2 == 0) {
alert('Even number');
} else {
return true;
}
}
function allnumeric(inputtxt)
{
var numbers = /^[0-9]+$/;
var qty = form2.qty.value;
if(qty.match(numbers) && (form2.product.value != ""))
{
if(qty & 1) // even number
return true;
else
alert('Even number');
return false;
}
else
{
alert('Please input numeric characters only or fill in the product field')
return false;
}
}
<form id="form2" name="form2" method="post" action="booking-printlabel2.asp?insert=yes" onsubmit="return allnumeric()">
<input name="product" type="text" id="product" style="height:55px;font-size:30pt;" size="10"/>
<input name="qty" type="text" id="qty" style="height:55px;font-size:30pt;" size="3"/>
<input type="submit" name="Print Labels2" id="Print Labels2" value="Print Labels" style="height:55px;font-size:30pt;"/>
</form>

how to validate multiple textboxes on button click using jquery

In my application I have five textboxes.
When submit button click I want to validate these textboxes.
Validation should be at least 3 textboxes should have value in it.
Old way is using jQuery each loop we can check but is there any other way to do it ?
$("#submitBtn").on("click", function(){
var count = 0;
$(".textboxesDiv input").each(function () {
if($(this).val() != "" && $(this).val() != null && $(this).val() != undefined){
count++;
}
});
if(count > 2 )
{
alert("3 or more");
}
else{
alert("lessa than 3");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="textboxesDiv">
<input type="text" id="textbox1" >
<input type="text" id="textbox2" >
<input type="text" id="textbox3" >
<input type="text" id="textbox4" >
<input type="text" id="textbox5" >
</div>
<input type="submit" id ="submitBtn" name="button"/>
https://jsfiddle.net/7Lmgbbng/1/
Check this example
http://jsfiddle.net/ggChris/mfbaxkfp/
<input id="AccountText" type="text" name="AccountText" value="" class="form-control" placeholder="Name" required=''/>
<input class="button" type="submit" value="submit">
$(document).ready(function(){
$('.button').click(function(){
if ($('input#AccountText').val() == ""){
alert('Please complete the field');
}
});
});
or you can use jquery validation
https://jqueryvalidation.org/

Using jQuery to validate checkboxes and input text values

I need your help,
Is there a way one can possible use the all so powerful jQuery to validate the following conditions before enabling button?
If the user inputs a value in the text box and then checks one of the checkboxes, then enable the button
If the user already has a value present in the text, and then checks one of the checkboxes, then enable the button
How can this be written in jQuery, from my perspective this would some lenghty form field checking no?
Here's the HTML markup:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<input type="button" value="Add To Calendar" disabled>
<br>
<input type="checkbox" name="dategroup"><input type="text" id="date1">
<br>
<input type="checkbox" name="dategroup"><input type="text" id="date2">
<br>
<input type="checkbox" name="dategroup"><input type="text" id="date3">
</body>
</html>
This might get you started. You can make the field validation as complex or simple as you wish.
$('input[type=checkbox]').click(function(){
var tmp = $(this).next('input').val();
//validate tmp, for example:
if (tmp.length > 1){
//alert('Text field has a value');
$('#mybutt').prop('disabled',false);
}else{
//alert('Please provide a long value in text field');
$('#mybutt').prop('disabled', true);
$(this).prop('checked',false);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input id="mybutt" type="button" value="Add To Calendar" disabled>
<br>
<input type="checkbox" name="dategroup"><input type="text" id="date1">
<br>
<input type="checkbox" name="dategroup"><input type="text" id="date2">
<br>
<input type="checkbox" name="dategroup"><input type="text" id="date3">
Try this way..
$('input').on('change input', function() {
$input = $('input');
$button = $('input[type="button"]');
var arr = [];
$input.each(function() {
if ($(this).attr('type') !== 'button') {
arr.push(check($(this)));
arr.indexOf(false) == -1 ? $button.removeAttr('disabled') : $button.attr('disabled', 'disabled');
}
})
})
function check(elem) {
if ($(elem).attr('type') == 'checkbox' && $(elem).is(':checked')) return true;
if ($(elem).attr('type') == 'text' && $(elem).val().trim().length) return true;
return false;
}
$('input').on('change input', function() {
$input = $('input');
$button = $('input[type="button"]');
var arr = [];
$input.each(function() {
if ($(this).attr('type') !== 'button') {
arr.push(check($(this)));
arr.indexOf(false) == -1 ? $button.removeAttr('disabled') : $button.attr('disabled', 'disabled');
}
})
})
function check(elem) {
if ($(elem).attr('type') == 'checkbox' && $(elem).is(':checked')) return true;
if ($(elem).attr('type') == 'text' && $(elem).val().trim().length) return true;
return false;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" value="Add To Calendar" disabled>
<br>
<input type="checkbox" name="dategroup">
<input type="text" id="date1">
<br>
<input type="checkbox" name="dategroup">
<input type="text" id="date2">
<br>
<input type="checkbox" name="dategroup">
<input type="text" id="date3">

form not validating - javascript

bit of a noob with form validation. I'm trying to get this form to validate on the required fields, and something's amiss. Here's what I'm working with:
html:
<form action="../visit/thankyou.html" method="post" id="vsurvey">
<input type="hidden" name="id" value="503" />
<fieldset>
<legend>Group and Coordinator Information</legend>
<label><span>Group Leader Name<span style="color:#cc2d30">*</span></span>
<input type="text" name="question_8149" />
</label>
<label><span>Email<span style="color:#cc2d30">*</span></span>
<input type="text" name="question_8155" />
</label>
<label><span>Phone<span style="color:#cc2d30">*</span></span>
<input type="text" name="question_8156" />
</label>
<label><span>School/Organization<span style="color:#cc2d30">*</span></span>
<input type="text" name="question_8159" />
</label>
<label><span>Program</span>
<input type="text" name="question_8180" />
</label>
<label><span>Grade(s)</span>
<input type="text" name="question_8181" />
</label>
<label><span>Number of Participants<span style="color:#cc2d30">*</span></span>
<input type="text" name="question_8182" />
</label>
</fieldset>
<fieldset>
<label><span>Preferred Date<span style="color:#cc2d30">*</span></span>
<input class="date" type="text" id="question_8185" name="question_8185" />
</label>
<label><span>Second Preference Date<span style="color:#cc2d30">*</span></span>
<input class="date" type="text" id="question_8186" name="question_8186" />
</label>
<label><span>Third Preference Date<span style="color:#cc2d30">*</span></span>
<input class="date" type="text" id="question_8187" name="question_8187" />
</label>
<label>Special Accommodations
<input type="text" name="question_8174" />
</label>
</fieldset>
<label>What is the purpose or desired outcome of this visit?
<textarea name="question_13026"></textarea>
</label>
<label>How did you learn about our Group Visit Program?
<textarea name="question_8176"></textarea>
</label>
<label>Comments
<textarea name="question_8184"></textarea>
</label>
<input type="submit" id="sbutton" value="Submit Request" />
</form>
js:
function validateForm() {
var x = document.forms["vsurvey"]["question_8149"].value;
if (x == null || x == "") {
alert("Please fill in the Group Leader's name.");
return false;
}
var x = document.forms["vsurvey"]["question_8155"].value;
if (x == null || x == "") {
alert("Please fill in the email field.");
return false;
}
var x = document.forms["vsurvey"]["question_8156"].value;
if (x == null || x == "") {
alert("Please fill in the phone field.");
return false;
}
var x = document.forms["vsurvey"]["question_8159"].value;
if (x == null || x == "") {
alert("Please fill in the School/Organization field.");
return false;
}
var x = document.forms["vsurvey"]["question_8182"].value;
if (x == null || x == "") {
alert("Please indicate the number or participants.");
return false;
}
var x = document.forms["vsurvey"]["question_8185"].value;
if (x == null || x == "") {
alert("Please enter your preferred date.");
return false;
}
var x = document.forms["vsurvey"]["question_8186"].value;
if (x == null || x == "") {
alert("Please enter your second date preference.");
return false;
}
var x = document.forms["vsurvey"]["question_8187"].value;
if (x == null || x == "") {
alert("Please enter your third date preference.");
return false;
}
}
http://jsfiddle.net/blackessej/9a6BJ/1/
Currently the form submits the info anyway, but without sending the user to the thankyou page, if all required fields aren't filed in. If all required fields are filed, the thankyou page gets called.
You're not calling validatorForm. Your input button needs to be the following
<input type="submit" id="sbutton" value="Submit Request" onclick="return validateForm()" />
Or use the onsubmit event of your form
<form action="../visit/thankyou.html" method="post" id="vsurvey" onsubmit="return validateForm()">
You need to create an onSubmit event to call validateForm:
document.getElementById('vsurvey').onsubmit = validateForm;

Is insertAdjacentHTML problematic?

I have two functions. The first is the one in which all the input elements will be checked to make sure they are filled correctly. Every thing works well but as the second function comes into action ( The second function 'newInput()' adds inputs ) the first function can not be applied anymore.
The debugger says the emailSec in atpositionSec = emailSec.indexOf("#"), is undefined.
Does any body know the solution??
The markup goes here:
<--!The HTML-->
<form method="post" action="" id="cms" name="cms" onSubmit="return error()">
<table>
<tbody id="myInput">
<tr>
<td>
<label>Role:<span> *</span></label>
<input type="text" name="role" id="role" value="" class="required span3" role="input" aria-required="true" />
</td>
<td>
<label>Email:<span> *</span></label>
<input type="email" name="emailSec" id="emailSec" value="" class="required span3" role="input" aria-required="true" />
</td>
<td>
<button style="height: 20px;" title='Add' onclick='newInput()'></button>
</td>
</tr>
</tbody>
<input type="hidden" name="count" id="count" vale=""/>
</table>
<input type="submit" value="Save Changes" name="submit" id="submitButton" title="Click here!" />
</form>
The First Function:
function error()
{
var emailSec = document.forms['cms']['emailSec'].value,
role = document.forms['cms']['role'].value,
atpositionSec = emailSec.indexOf("#"),
dotpositionSec = emailSec.lastIndexOf(".");
if( topicSec == '' || topicSec == null)
{
alert ("Write your Topic!");
return false;
}
else if(role == '' || role == null)
{
alert ("Enter the Role of the email owner!");
return false;
}
else if(emailSec == '' || emailSec == null || atpositionSec < 1 || dotpositionSec < atpositionSec+2 || dotpositionSec+2 >= emailSec.length)
{
alert ("Enter a valid Email!");
return false;
}
else return true;
}
The Second Function:
//The Javascript - Adding Inputs
var i = 1,
count;
function newInput()
{
document.getElementById("myInput").insertAdjacentHTML( 'beforeEnd', "<tr><td><input type='text' name='role" + i + "' id='role' value='' class='required span3' role='input' aria-required='true' /></td><td><input type='email' name='emailSec" + i + "' id='emailSec' value='' class='required span3' role='input' aria-required='true' /></td><td><button style='height: 20px;' title='Remove' onclick='del(this)'></button></td></tr>");
count = i;
document.forms["cms"]["count"].value = count;
i++;
}
// Removing Inputs
function del(field)
{
--count;
--i;
document.forms["cms"]["count"].value = count;
field.parentNode.parentNode.outerHTML = "";
}
The problem is that after the first addition, document.forms['cms']['emailSec'] becomes an array with all the elements with the name emailSec, so you would need to validate all of them individually using document.forms['cms']['emailSec'][i].
To save you some trouble, you could use the pattern attribute of the input elements in html5 to do this automatically. Furthermore, you could use something like <input type="email" required /> which I think will do almost all the work for you.

Categories