I have form with validations using Javascript. All of the drop downs are not validating. Any help?
<form id="itsp-form" method="post" action="http://www.url.com/save_itsp.php">
<label class="custom">Company name</label>
<input id="company_name" type="text" name="company_name" />
<label class="custom">Company URL</label>
<input id="company_url" type="text" name="company_url" />
<label class="custom">Company address</label>
<input id="company_address" type="text" name="company_address" />
<label class="custom">Type of business</label>
<select id="type_of_business[]" name="type_of_business[]" multiple="multiple">
<option value="" selected="selected"></option>
<option value="enterprise">Business sector/Enterprise</option>
<option value="residential">Residential</option>
<option value="wholesale">Wholesale VoIP Carrier</option>
<option value="other">Other</option>
</select>
<label class="custom">Areas served</label>
<select id="areas_served[]" name="areas_served[]" multiple="multiple">
<option value="" selected="selected"></option>
<option value="USA">USA</option>
<option value="Canada">Canada</option>
<option value="other">Other</option>
</select>
<br />
<label class="custom">Sales contact</label><br />
<h4>Name</h4>
<input id="sales_name" type="text" name="sales_name" />
<h4>Phone</h4>
<input type="text" name="sales_phone" />
<h4>Email</h4>
<input type="text" name="sales_email" />
<br />
<label class="custom">Testing contact</label><br />
<h4>Name</h4>
<input id="testing_name" type="text" name="testing_name" />
<h4>Phone</h4>
<input type="text" name="testing_phone" />
<h4>Email</h4>
<input type="text" name="testing_email" />
<br />
<label class="custom">Switch Platform</label>
<select id="switch_platform[]" name="switch_platform[]" multiple="multiple">
<option value="" selected="selected"></option>
<option value="asterisk">Asterisk</option>
<option value="broadsoft">Broadsoft</option>
<option value="metaswitch">Metaswitch</option>
<option value="sipx">SipX/eZuce</option>
<option value="other">Other</option>
</select>
<label class="custom">Interested In Testing</label>
<select id="interested_in_testing[]" name="interested_in_testing[]" multiple="multiple">
<option value="" selected="selected"></option>
<option value="atas">ATAs</option>
<option value="ip_phones">IP Phones</option>
<option value="gateways">Gateways</option>
<option value="ip_pbx">IP PBX</option>
</select>
<input type="submit" id="submit" value="Submit" />
<script>
$('#submit').click(function() {
$('.error').hide();
var hasError = false;
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if (($("#company_name").val() == '') || ($("#type_of_business[]").val() == '')) {
$("#errors").after('<span class="error">Please enter your Company name.</span>');
hasError = true;
}
if (($("#company_url").val() == '') || ($("#company_address").val() == '')) {
$("#errors").after('<span class="error">Please enter your Company information.</span>');
hasError = true;
}
if ($("#areas_served[]").val() == '') {
$("#errors").after('<span class="error">Please enter your Areas served.</span>');
hasError = true;
}
if ($("#type_of_business[]").val() == '') {
$("#errors").after('<span class="error">Please enter your Type of business.</span>');
hasError = true;
}
if ($("#sales_name").val() == '') {
$("#errors").after('<span class="error">Please enter your Sales contact information.</span>');
hasError = true;
}
if ($("#testing_name").val() == '') {
$("#errors").after('<span class="error">Please enter your Tester contact information</span>');
hasError = true;
}
if ($("#switch_platform[]").val() == '') {
$("#errors").after('<span class="error">Please enter your Switch platform</span>');
hasError = true;
}
if ($("#interested_in_testing[]").val() == '') {
$("#errors").after('<span class="error">Please enter your Testing interests.</span>');
hasError = true;
}
if(hasError == true) { return false; }
});
Your problem is that your ids are using square brackets [] which in jquery is an attribute-equals-selector. See http://api.jquery.com/attribute-equals-selector/
I would recommend not using square brackets in your id strings. Although permissible by html5, I would stick to using standard word and digit characters [a-zA-Z_0-9] to avoid issues with javascript tools and libraries
If you still want to use square brackets you must escape them. See jQuery selector for inputs with square brackets in the name attribute.
If you are using <input type='submit'>, the form will be submitted no matter what.
Try using <input type='button'> it may work then.
Related
I'm trying to limit the amount of checkboxes able to be checked according to what select option the user chooses i.e. option1 = 1 checkbox option 2 = 2 checkboxes and if they try to choose more then alert the user and .prop("checked", false).
but i just get weird stuff happening and i can't figure why please help!!
html:
<form>
<select onclick="systemSelected();" class="mySelectBox">
<option value="1">option1</option>
<option value="2">option2</option>
<option value="3">option3</option>
<option value="4">option4</option>
<option value="5">option5</option>
</select>
</form>
<form onclick="limitCheckbox(userSelected);">
<input type="checkbox" name="box1">
<input type="checkbox" name="box2">
<input type="checkbox" name="box3">
<input type="checkbox" name="box4">
<input type="checkbox" name="box5">
</form>
javascript:
var userSelected = 0;
function systemSelected() {
$(".mySelectBox option").each(function(){
if ($(this.selected)) {
userSelected = parseInt($(".mySelectBox").val());
}
});
}
function limitCheckbox(userSystem) {
$("input[type=checkbox]").click(function(){
if($("input[type=checkbox]:checked".length > userSystem)) {
$(this).prop("checked", false);
alert("too many numbers");
} else if ($("input[type=checkbox]:checked".length === 0 )) {
alert("please select a game too play");
}
});
}
Don't use alerts (Why should a user feel stupid)
Use the disabled property (Make a user see & know)
var $ckb = $('[name*=box]'),
$sel = $('.mySelectBox');
function ckkk () {
var ckd = $ckb.filter(":checked").length,
max = parseInt($sel.val(), 10);
if(ckd > max) $ckb.prop({checked:false, disabled:false});
else $ckb.not(":checked").prop({disabled: ckd >= max});
}
$ckb.add($sel).on("change", ckkk);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="mySelectBox">
<option value="1">option1</option>
<option value="2">option2</option>
<option value="3">option3</option>
<option value="4">option4</option>
<option value="5">option5</option>
</select>
<input type="checkbox" name="box1">
<input type="checkbox" name="box2">
<input type="checkbox" name="box3">
<input type="checkbox" name="box4">
<input type="checkbox" name="box5">
use $("input[type=checkbox]").on('change',function(){ selector which will fire event on every change of checkbox. And you can manage your cases with conditions in it.
Please check below snippet.
var userSelected = 0;
$("input[type=checkbox]").on('change',function(){
if($("input[type=checkbox]:checked").length > parseInt($(".mySelectBox").val())) {
$(this).prop("checked", false);
alert("too many numbers");
} else if ($("input[type=checkbox]:checked").length === 0 ) {
alert("please select a game too play");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<select class="mySelectBox">
<option value="1">option1</option>
<option value="2">option2</option>
<option value="3">option3</option>
<option value="4">option4</option>
<option value="5">option5</option>
</select>
</form>
<form>
<input type="checkbox" name="box1">
<input type="checkbox" name="box2">
<input type="checkbox" name="box3">
<input type="checkbox" name="box4">
<input type="checkbox" name="box5">
</form>
$('input:checkbox').change(function() {
var number = $('.mySelectBox option:selected').val();
if ($('input:checkbox:checked').length > number) {
alert('more than selected')
$(this).prop('checked', false);//dont check the click checkbox
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<select class="mySelectBox">
<option value="1">option1</option>
<option value="2">option2</option>
<option value="3">option3</option>
<option value="4">option4</option>
<option value="5">option5</option>
</select>
</form>
<form>
<input type="checkbox" name="box1">
<input type="checkbox" name="box2">
<input type="checkbox" name="box3">
<input type="checkbox" name="box4">
<input type="checkbox" name="box5">
</form>
html-
<label >Parameter Name: </label>
<select id="name" name="name" required>
</select> </br> </br>
<label >Address: </label>
<select class= "address" type=text id="address" name="address" style="width:14em;" required>
</select> </br> </br>
<label >Data Size: </label> </br>
<select type=text id=sizeSelect name="size"style="width: 14em;" required>
</select> </br> </br>
js-
function processFile(e) {
var file = e.target.result,
results;
if (file && file.length) {
results = file.split(",");
$('select').children().remove();
for (var i = 1; i < results.length; i=i+8) {
if(typeof results[i] !== 'undefined') {
$("select[name='address']").each(function() {
$(this).append('<option val="i">' + results[i] + '</option>');
});
}
if(typeof results[i+6] !== 'undefined') {
$("select[name='name']").each(function() {
$(this).append('<option val="i">' + results[i+6] + '</option>');
});
}
if(typeof results[i+1] !== 'undefined') {
$("select[name='size']").each(function() {
$(this).append('<option val="i">' + results[i+1] + '</option>');
});
}
}
}
}
I want to somehow allow the interface so that when the client selects the address option with value 1 then the name and size of that value are selected automatically. Any ideas?
Using jQuery .val() you can get and set the values for select tags.
If the options of each select contains an attribute with a value of the next select option to be selected, you can reduce all to:
$(function () {
$('#address').on('change', function(e) {
var optionSelected = $(this).find('option:selected');
$('#name').val(optionSelected.attr('name'));
$('#sizeSelect').val(optionSelected.attr('sizeSelect'));
})
});
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<form>
<label>Parameter Name: </label>
<select id="name" name="name" required>
<option></option>
<option value="1" >Name 1</option>
<option value="2">Name 2</option>
</select><br><br>
<label>Address: </label>
<select class="address" type=text id="address" name="address" style="width:14em;" required>
<option></option>
<option value="1" name="1" sizeSelect="1">Address 1</option>
<option value="2" name="2" sizeSelect="2">Address 2</option>
</select> <br><br>
<label>Data Size: </label> </br>
<select type=text id=sizeSelect name="size" style="width: 14em;" required>
<option></option>
<option value="1">Size 1</option>
<option value="2">Size 2</option>
</select> <br> <br>
</form>
I am creating a form:
<input type="checkbox" id="chk1">1<select name="sel1" id="sel1" class="sel">
<option value="..."></option>
<option value="a">a</option>
<option value="b">b</option>
<input type="text" name="txt1" id="txt1" class="txt"/><br />
<input type="checkbox" id="chk2">2<select name="sel2" id="sel2" class="sel">
<option value="..."></option>
<option value="a">a</option>
<option value="b">b</option>
<input type="text" name="txt2" id="txt2" class="txt"/><br/>
<input type="checkbox" id="chk3">3<select name="sel3" id="sel3" class="sel">
<option value="..."></option>
<option value="a">a</option>
<option value="b">b</option>
<input type="text" name="txt3" id="txt3" class="txt"/><br />
<button type="submit" class="btn btn-default">Submit</button>
And I am trying to create a block on the submit button so that if a checkbox is checked: the textbox can't be empty, and the dropdown has to have a different value than '...' If either of those is the case, user clicks 'submit' and nothing should happen...if all is satisfied though, then they click submit, and it goes through.
Javascript/jQuery logic I'm aiming for is something like
if ($(":checkbox:checked").length != 0) {
if ($(".txt").val === ("")) {
return false;
}
else {return true}
if ($(".sel").val === "...") {
return false;
}
else {return true}
}
DEMO
First of all I would like to correct your html and do wrap each checkbox,input, select in a group element so that you can easily get its corresponding values. You select had syntax error and select is not a self closing tag like <select/> instead it is <select>..</select>. Hence below is the updated code:
<form id="frmDetails">
<div class="container"> <!--wrap them in each container-->
<input type="checkbox" id="chk1" value="1"/>
<select name="sel1" id="sel1" class="sel">
<option value="0">Select</option>
<option value="a">a</option>
<option value="b">b</option>
</select>
<input type="text" name="txt1" id="txt1" class="txt"/><br />
</div>
<div class="container">
<input type="checkbox" value="2" id="chk2"/>
<select name="sel2" id="sel2" class="sel">
<option value="0">Select</option>
<option value="a">a</option>
<option value="b">b</option>
</select>
<input type="text" name="txt2" id="txt2" class="txt"/><br/>
</div>
<div class="container">
<input type="checkbox" id="chk3" value="3"/>
<select name="sel3" id="sel3" class="sel">
<option value="0">Select</option>
<option value="a">a</option>
<option value="b">b</option>
</select>
<input type="text" name="txt3" id="txt3" class="txt"/><br />
</div>
<button type="submit" class="btn submit btn-default">Submit</button>
</form>
Then your js would be as below:
var valid; //A global variable to check the validation
function validate(){
valid=true; //set it to true at beginning
$.each($('#frmDetails input:checkbox'),function(){
//loop through each checkbox
if($(this).is(":checked")) //if it is checked
{
var selected=$(this).siblings('select').find('option:selected').val()
//get selected value of its select element
var text=$(this).siblings('input').val();
//get value entered in its corresponding textbox
if(text=="" || selected=="0") if text="" or selected value=0
{
valid=false;//set valid to false
return valid;//return it
}
}
});
return valid; //else this will be true
}
$(".submit").on('click',function(e){
e.preventDefault(); //prevent default action of submit
if(validate()) //validate returns true or false
{
$("#frmDetails").submit(); //submit the form if valid
}
else
{
alert('Form is invalid, You cannot submit it');
//do whatever your want here
}
});
event.preventDefault() will do that blocking for you. It will prevent the form to get submitted. Instead of returning false like native javascript. Collect that returning result in a cache variable then execute event.preventDefault() when it evaluated to false.
use Jquery to prevent form submitting
$("button[type='submit']").on("click", function(e){
e.preventDefault();
if ($(":checkbox:checked").length != 0) {
if ($(".txt").val === ("")) {
return false;
}
else {$("#myForm").submit();
}
if ($(".sel").val === "...") {
return false;
}
else {$("#myForm").submit();}
}
});
So, what I want to accomplish here is to prevent people from entering the rest of the form until they focus on the first section by hiding the last section until the value of a certain field is greater than nothing.
Here is my HTML:
<div class="fieldcontainer">
<label>E-mail:</label>
<input type="email" name="email" maxlength="100" id="email" required>
</div>
<br><br>
<div id="projectinformation" style="display:none">
<h3>Project Information</h3>
<div class="fieldcontainer">
<label>Project Name:</label>
<input type="text" name="project_name" maxlength="70" required>
</div>
<br><br>
<div class="fieldcontainer">
<label>Project Number:</label>
<input type="text" name="project_number" required>
</div>
<br><br>
<div class="fieldcontainer">
<label>Business Unit:</label>
<select name="business_unit" required>
<option>--Select--</option>
</select>
</div>
<br><br>
<div class="fieldcontainer">
<label>Project Address:</label>
<input type="text" name="address" required>
</div>
<br><br>
<div class="fieldcontainer">
<label>Number of users on site:</label>
<select id="numberofstaff">
<option class="staffselection" value="">--Select--</option>
<option class="staffselection" value="smalljobsite">1-3 staff</option>
<option class="staffselection" value="mediumjobsite">4-7 staff</option>
<option class="staffselection" value="largejobsite">8+ staff</option>
</select>
</div>
</div>
Here is my JS:
while (document.getElementById('email').value > ""){
document.getElementById('projectinformation').style.display = 'initial';
}
You'd probably want an event handler for that, and check the inputs value length, then show the rest of the form
document.getElementById('email').addEventListener('input', function() {
if ( this.value.length > 0 ) {
document.getElementById('projectinformation').style.display = 'block';
}
}, false);
or in jQuery
$('#email').on('input', function() {
if (this.value.length > 0) $('#projectinformation').show();
});
Here is jQuery solution:
$("#email").keyup(function() {
if($(this).val().length)
$('#projectinformation').show();
else
$('#projectinformation').hide();
});
If you want to validate if it is a valid email and then show the form, you can do this: (https://stackoverflow.com/a/2855946/1845408):
function isValidEmailAddress(emailAddress) {
var pattern = new RegExp(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))#((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i);
return pattern.test(emailAddress);
};
$("#email").keyup(function() {
if(isValidEmailAddress($(this).val())) {
$('#projectinformation').show();
else
$('#projectinformation').hide();
});
I have been trying to make a form that validates phone number and name, but whenever submit is entered it just inputs the same messages whether the fields are filled out or not. The message constantly appears and I can't figure it out
ETA: http://jsfiddle.net/6W3uU/
<body>
<form id="contact">
<fieldset id="contactInformation">
<legend>Contact Information</legend>
<p id="error"></p>
<label id="name">Name:</label>
<br>
<input type="text">
<br>
<br>
<label id="phoneNumber">Phone Number:</label>
<br>
<input type="text">
<br>
<br>
<label id="eMail">E-Mail Address:</label>
<br>
<input type="text">
<br>
<br>
<label id="address">Address:</label>
<br>
<input type="text">
<br>
<br>
<label id="city">City:</label>
<br>
<input type="text">
<br>
<br>
<label id="postalCode">Postal Code:</label>
<br>
<input type="text">
<br>
<br>
<label id="province">Province</label>
<br>
<select id="province">
<option id="choose">Choose Your Province</option>
<option id="alberta">Alberta</option>
<option id="britishColumbia">British Columbia</option>
<option id="manitoba">Manitoba</option>
<option id="newBrunswick">New Brunswick</option>
<option id="newfoundland">Newfoundland and Labrador</option>
<option id="northwestTerritories">Northwest Territories</option>
<option id="noviaScotia">Nova Scotia</option>
<option id="nunavut">Nunavut</option>
<option id="ontario">Ontario</option>
<option id="pei">Prince Edward Island</option>
<option id="quebec">Quebec</option>
<option id="saskatchewan">Saskatchewan</option>
<option id="yukon">Yukon Territory</option>
<br>
<br>
<br>
<label id="shippingCheckbox">Is your shipping information the same as your contact information?
<input type="radio" id="sameInfo">
<label>
Yes it is
</label>
<br>
<br>
<input type="radio" id="notSameInfo">
<label>
No it is not
</label>
<br>
<br>
<input type="submit" id="submit" name="submit" value="Submit">
</form>
<br>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="js/script.js"></script>
</body>
</html>
And here is the script:
//script.js
var errorNotify = 'Sorry, we could not process your request because '
var errorField = [];
function formVal() {
var isValid = true;
for (var i = 0; i < errorField.length; i++ ) {
$(errorField[i]).removeClass('error');
}
errorField = [];
if(!nameCheck()) {
isValid = false;
}
if(!phoneCheck()) {
isValid = false;
}
if (isValid === false) {
$('#error').html(errorNotify).hide().slideDown('slow');
for (var i = 0; i < errorField.length; i++) {
$(errorField[i]).addClass('error');
}
errorNotify = 'Sorry, we could not process your request because ';
}
function nameCheck(){
if ($('#name').val() === '') {
errorNotify += ' you did not enter your name.';
errorField.push($('#name'));
return false;
} else {
return true;
}
}
function phoneCheck(){
var phoneCheck = $('#phoneNumber').val();
if (phoneCheck === '') {
errorNotify += ' you did not enter your phone number.';
errorField.push($('#phoneNumber'));
return false;
} else if (phoneCheck.length !== 10) {
errorNotify += 'please enter a 10 digit phone number';
errorField.push($('#phoneNumber'));
}
else if (isNaN(parseInt(phoneCheck))) {
errorNotify += 'you have entered a letter, please enter a number';
errorField.push($('#phoneNumber'));
}
else {
return true;
}
}
return isValid;
}
$(function () {
$('#contact').submit(function() {
return formVal();
});
});
You have your ids on the label tags, not the input fields, change
<label id="name">Name:</label>
<br>
<input type="text">
to
<label for="name">Name:</label>
<br>
<input id="name" type="text">
etc