I'm making a small web app using JQuery Mobile and Multi Page architecture.
I have a form as my second page. When I click the submit button, I get this error on my console. I need this web app to work on my phone but I'm testing it on my PC browser to see for possible errors.
I'm using localStorage to save the form data in an array in the phone's memory.
Why am I getting this error? I tried with "get" but it just refreshes and takes me back to my home page.
below is my form code:
<div data-role="page" id="entry_page">
<div data-role="header">
Clear
<h3 id="chickenNameHeader"></h3>
<a href="#" onclick="showLogs()" data-icon="action" >Show Logs</a>
</div>
<div class="form-container">
<form action="" method="post">
<label for="ID_input">ID:</label>
<input id="ID_input" type="number" placeholder="xxxx">
<label for="weight_input">Weight (g):</label>
<input id="weight_input" type="number" step="any" min="0" max="10000" placeholder="0. → 10000">
<label for="eggs_input">Eggs laid:</label>
<input id="eggs_input" type="number" min="0" max="4" placeholder="0 → 4">
<label for="grain_input">Grain eaten (g):</label>
<input id="grain_input" type="number" step="any" min="0" max="1000" placeholder="0. → 1000">
<label for="category_input">Category:</label>
<select id="category_input" required="true">
<option value="empty" selected></option>
<option value="poor">Poor</option>
<option value="average">Average</option>
<option value="good">Good</option>
</select>
<button id="submitBtn" type="submit" name="button">Save log entry</button>
</form>
</div>
<div data-role="footer" class="ui-bar">
<a id="6" href="#" onclick="traverse(this)" data-icon="arrow-r" data-ajax="false" >Next</a>
<a id="7" href="#" onclick="traverse(this)" data-icon="arrow-l" data-ajax="false" >Previous</a>
<a id="5" onclick="getID(this)" href="#" data-icon="home" >Home</a>
</div>
</div>
Below is my submit button handler in JS:
//Initialise entry page for the first time and handle form submission validation
$(document).delegate("#entry_page","pageinit",function()
{
if (navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(onSuccess, onError);
}
changeHeaderName("#chickenNameHeader");
$("#submitBtn").click(function(event)
{
var id = $.trim($("#ID_input").val());
var weight = $.trim($("#weight_input").val());
var eggs = $.trim($("#eggs_input").val());
var grain = $.trim($("#grain_input").val());
var category = $("#category_input").val();
var error_free = 1;
if(id == "")
{
alert("Please enter a 4 digit ID");
error_free = 0;
}
if(weight == "")
{
alert("Please enter the amount of weight");
error_free = 0;
}
if(eggs == "")
{
alert("Please enter the amount of eggs laid");
error_free = 0;
}
if(grain == "")
{
alert("Please enter the amount of grain eaten");
error_free = 0;
}
if(category == "empty")
{
alert("Please select a category");
error_free = 0;
}
if(Number(id) < 1000 || Number(id) > 9999)
{
alert("ID must be 4 digits");
error_free = 0;
}
if(Number(weight) < 0 || Number(weight) > 10000)
{
alert("Weight must be between 0. and 10000");
error_free = 0;
}
if(Number(grain) < 0 || Number(grain) > 1000)
{
alert("Grains eaten must be between 0. and 1000");
error_free = 0;
}
if(latitude == "" || longitude == "")
{
alert("Location not given. Please allow location access and refresh the application");
error_free = 0;
}
if(dateTime == "")
{
alert("Date & Time not acquired");
error_free = 0;
}
if(!Boolean(error_free))
{
alert("Error saving log. Please fix problems and try again.");
event.preventDefault();
}
else
{
var item = {
id:id,
dateTime:dateTime,
latitude:latitude,
longitude:longitude,
weight:weight,
eggs:eggs,
grain:grain,
category:category };
switch (chickenNumber) {
case 0:
foghorn_items.push(item);
localStorage.foghorn_items = JSON.stringify(foghorn_items);
break;
case 1:
little_items.push(item);
localStorage.little_items = JSON.stringify(little_items);
break;
case 2:
tweety_items.push(item);
localStorage.tweety_items = JSON.stringify(tweety_items);
break;
case 3:
hawk_items.push(item);
localStorage.hawk_items = JSON.stringify(hawk_items);
break;
case 4:
bertha_items.push(item);
localStorage.bertha_items = JSON.stringify(bertha_items);
break;
}
alert("Log saved");
}
});
});
EDIT: I'm using Nginx as my web server if that helps.
Putting "error_page 405 =200 $uri;" in the Nginx.conf config file made the error go away, but yet to see if my data is getting stored in the memory.
Related
I tried to build a validation form using JavaScript which handles these errors:
The Name field should not be empty
The phone number field can contain only numbers (exactly 10 numbers)
One option should be selected (radio)
At least one car from checkboxes is selected and at max 3 cars
But the problem with my code is it has not worked in all cases. I mean if I selected submit it shows me the error message just in the name field, not on other fields.
For example here -
here my HTML code
<body>
<div class="MainBackground">
<h1 id="title">Car Company</h1>
</div>
<div class="cars">
<form method="POST" name="form-car" id="form-car">
<p id="decription"> users' request</p>
<div id="name_div">
<label id="lable-name" for="name">Name: </label>
<input id="name" type="text" name="yourName" placeholder="Enter your name"> <br>
<span id="errorname"></span>
</div>
<br> <br>
<label id="lable-Phone" for="Phone">Phone:</label>
<input id="phone" type="text" name="phonefild" placeholder="Enter your Phone Number"> <br>
<span id="errorpass"></span>
<br> <br>
<label id="lable-age" for="Age">Age:</label>
<br>
<input type="radio" name="group1" value="T"> 18-25
<br>
<input type="radio" name="group1" value="A"> 26-35
<br>
<input type="radio" name="group1" value="O"> 35-55
<br>
<input type="radio" name="group1" value="AO"> 36-80
<br>
<input type="radio" name="group1" value="VO"> 80-95
<br>
<span id="radioerorr"></span>
<br> <br>
<label for="check">Choice cars to tested</label>
<br>
<input class="checkbox" type="checkbox" id="option1" name="car1" value="BMW">
<label for="vehicle1">BMW</label><br>
<input class="checkbox" type="checkbox" id="option2" name="car2" value="Ferrari">
<label for="vehicle2">Ferrari</label><br>
<input checkbox="checkbox" type="checkbox" id="option3" name="car3" value="Ford">
<label for="vehicle3">Ford</label><br>
<input class="checkbox" type="checkbox" id="option4" name="car4" value="Audi">
<label for="vehicle4">Audi</label><br>
<input class="checkbox" type="checkbox" id="option5" name="car5" value="Cadillac">
<label for="vehicle5">Cadillac</label><br>
<span id="checkboxerorr"></span>
<br> <br>
<div class="center">
<button onclick="return validition()" id="submit" type="submit" name="button">submit</button>
<button id="reset" type="reset" name="button">reset</button>
</div>
</form>
</div>
And here my javascript code
function validition() {
var phoneinpute = document.getElementById('phone').value;
var radios = document.getElementsByTagName('input');
var value;
var inputs = document.getElementsByTagName("input");
var count1 = 0;
var count2 = 0;
var regex = /(5|0)([0-9]{8})$/;
if (document.getElementById('name').value == "") {
document.getElementById('errorname').innerHTML = "name should not be empty";
document.getElementById('name').style.borderColor = "red";
return false;
} else if (document.getElementById('name').value != "") {
document.getElementById('errorname').innerHTML = "";
document.getElementById('name').style.borderColor = "green";
}
if (regex.test(phoneinpute)) {
document.getElementById('errorpass').innerHTML = "";
document.getElementById('phone').style.borderColor = "green";
//return true;
} else {
document.getElementById('errorpass').innerHTML = "Invalide phone number";
document.getElementById('phone').style.borderColor = "red";
return false;
}
for (var i = 0; i < radios.length; i++) {
if (radios[i].type == "radio" && radios[i].checked) {
count1++;
}
if (count1 == 1) {
document.getElementById('radioerorr').innerHTML = "";
break;
} else {
document.getElementById('radioerorr').innerHTML = "one option should be selected";
return false
}
}
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].type == "checkbox" && inputs[i].checked) {
count2++;
}
if (count2 > 3 || count2 == 0) {
document.getElementById('checkboxerorr').innerHTML = "please choose at least one car and at most 3 cars";
return false
} else {
document.getElementById('checkboxerorr').innerHTML = "";
}
}
You are using return statements in your validations, if you return from your 1st validation (name box), the other code blocks will not execute. Use a local boolean to determine your return type and return that at the end of your function, that way, all of your validation code runs. Also, your radio button and checkbox validation logic is flawed, you set an error message on each iteration of the loop if count1 or count2 doesn't meet your conditions. Change it to something like the following:
function validition() {
let valid = true; //local boolean to return at the end of your function
var phoneinpute = document.getElementById('phone').value;
var radios = document.getElementsByTagName('input');
var value;
var inputs = document.getElementsByTagName("input");
var count1 = 0;
var count2 = 0;
var regex = /(5|0)([0-9]{8})$/;
//Name validation
if (document.getElementById('name').value == "") {
document.getElementById('errorname').innerHTML = "name should not be empty";
document.getElementById('name').style.borderColor = "red";
valid = false;
} else if (document.getElementById('name').value != "") {
document.getElementById('errorname').innerHTML = "";
document.getElementById('name').style.borderColor = "green";
}
//Phone number validation
if (regex.test(phoneinpute)) {
document.getElementById('errorpass').innerHTML = "";
document.getElementById('phone').style.borderColor = "green";
} else {
document.getElementById('errorpass').innerHTML = "Invalide phone number";
document.getElementById('phone').style.borderColor = "red";
valid = false;
}
//Radio button validation
for (var i = 0; i < radios.length; i++) {
if (radios[i].type == "radio" && radios[i].checked) {
count1++;
}
if (count1 == 1) {
document.getElementById('radioerorr').innerHTML = "";
break;
}
}
//check to see if you had a checked radio button, if not, add error
//and mark local boolean as false
if(count1 < 1){
document.getElementById('radioerorr').innerHTML = "one option should be selected";
valid = false;
}
//Checkbox validation
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].type == "checkbox" && inputs[i].checked) {
count2++;
}
}
//Do your checkbox validation after the for loop
if (count2 > 3 || count2 == 0) {
document.getElementById('checkboxerorr').innerHTML = "please choose at least one car and at most 3 cars";
valid = false;
} else {
document.getElementById('checkboxerorr').innerHTML = "";
}
//return your local boolean value
return valid;
}
I'm working on a basic webform for my beginning Javascript class. I pretty much have all my expected results (assignment covers input validation and storing elements in an array by name), except for the fact that when I submit the form, I'd like to give a 5 second delay from the time I hit submit to when the page redirects. This delay is so that user will be able to cancel the order.
From what we have learned in class so far, I would expect I perform this action with a setTimeout block of code- though I haven't been able to work that yet. My form submission is dependent on a true/false return value from the called function, and I'd like to delay that true value from hitting so quickly. I've attached my full HTML file but the block of code that I'm wondering why it isn't working in particular is this:
setTimeout(function() {
return true;
}, 5000);
The first problem I observe when debugging in Chrome is that this doesn't return the True value back to the surrounding code.
I think that something could be done with jQuery to circumvent this but we haven't covered any of that so I'd like to avoid going that route.
```
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta name="description" content="Costello Improved">
<meta http-equiv="Content-type" content="text/html;charset=UTF-8" />
<title>Costellos Pasta and Pizza</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<link rel="stylesheet" href="costello.css">
</head>
<body>
<form name="myForm" action="https://costello-pasta.glitch.me/order" id="myForm" method="POST" onsubmit="return calculateOrder(this)">
<div class="container">
<div class="row">
<div class="col-md-12" id="debug">Costello's Online Orders</div>
</div>
<div class="row">
<div class="col-md-4 label">Pasta Bowl</div>
<div class="col-md-4"> (basic price: $7.50)</div>
<div class="col-md-4"></div>
</div>
<div class="row">
<div class="col-md-4 label">Pasta</div>
<div class="col-md-4">
<div><input type="radio" name="pastatype" value="0" />Spaghetti (no extra cost)</div>
<div><input type="radio" name="pastatype" value="50" />Fettucine (add 50 cents)</div>
<div><input type="radio" name="pastatype" value="75" />Fusilli (add 75 cents)</div>
</div>
<div class="col-md-4 msg" id="radioLabel"></div>
</div>
<div class="row">
<div class="col-md-4 label">Sauce</div>
<div class="col-md-4">
<select name="sauce">
<option value="0">Pomodoro (no extra cost)</option>
<option value="50">Bolognese (add 50 cents)</option>
<option value="100">Alfredo (add $1.00)</option>
</select>
</div>
<div class="col-md-4"></div>
</div>
<div class="row">
<div class="col-md-4 label">Extras</div>
<div class="col-md-4">
<div><input type="checkbox" name="extras" value="200" />Side salad (add $2.00)</div>
<div><input type="checkbox" name="extras" value="100" />Bread sticks (add $1.00)</div>
</div>
<div class="col-md-4"></div>
</div>
<div class="row">
<div class="col-md-4 label">Name</div>
<div class="col-md-4"><input type="text" id="name" name="client_name" /></div>
<div class="col-md-4 msg" id="nameLabel"></div>
</div>
<div class="row">
<div class="col-md-4 label">Phone</div>
<div class="col-md-4"><input type="text" id="phone" value="" /></div>
<div class="col-md-4 msg" id="phoneLabel"></div>
</div>
<div class="row">
<div class="col-md-4 label"><input type="submit" value="Order" /></div>
<div class="col-md-4" id="totalcost"></div>
<div class="col-md-4 msg" id="submitMessage"></div>
</div>
</div>
</form>
</body>
<script>
function calculateOrder() {
var totalCost = 750;
//Storing Pasta radio buttons into array. Iterating through array and adding checked selection's value to the total cost.
var submitBool = true;
var pastaArray = document.getElementsByName('pastatype');
for (var i = 0; i < pastaArray.length; i++) {
if (pastaArray[i].checked == true) {
totalCost = totalCost + parseInt(pastaArray[i].value);
}
//Validating Pasta input
}
if (pastaArray[0].checked == false && pastaArray[1].checked == false && pastaArray[2].checked == false) {
document.getElementById('radioLabel').innerHTML = "Required field! (You must choose a pasta)";
submitBool = false;
} else {
document.getElementById('radioLabel').innerHTML = "";
}
//Storing sauce selection into an array. Adding price for selected option.
var sauceArray = document.getElementsByName('sauce');
totalCost = totalCost + parseInt(sauceArray[0].value);
//Storing extras selection(s) into an array. Adding prices for selected options.
var extraArray = document.getElementsByName('extras');
for (var x = 0; x < extraArray.length; x++) {
if (extraArray[x].checked == true) {
totalCost = totalCost + parseInt(extraArray[x].value);
}
}
//Validating Name input
if (document.getElementById('name').value == "") {
document.getElementById('nameLabel').innerHTML = "Required field! Enter your name.";
submitBool = false;
} else {
document.getElementById('nameLabel').innerHTML = "";
}
//Validating Phone Number Input
var phone = document.getElementById('phone').value;
phone = phone.toString();
if (document.getElementById('phone').value == null) {
document.getElementById('phoneLabel').innerHTML = "Required field! Enter your phone number.";
submitBool = false;
} else if (phone[3] != "-") {
document.getElementById('phoneLabel').innerHTML = "Enter in 888-888-8888 format!";
submitBool = false;
} else if (phone[7] != "-") {
document.getElementById('phoneLabel').innerHTML = "Enter in 888-888-8888 format!";
submitBool = false;
} else if (phone.length > 12 || phone.length < 12) {
document.getElementById('phoneLabel').innerHTML = "Enter in 888-888-8888 format!";
submitBool = false;
} else {
document.getElementById('phoneLabel').innerHTML = "";
}
//Form runs if input has been valid in all input options
if (submitBool == false) {
return false;
} else if (submitBool == true){
var preFixed = totalCost / 100;
var postFixed = preFixed.toFixed(2);
document.getElementById('totalcost').innerHTML = "Total Bill: $" + postFixed;
document.getElementById('submitMessage').innerHTML = "Order is being processed, <a>cancel?</a>"
setTimeout(function() {
return true;
}, 5000);
}
}
</script>
</html>
```
You can use the onSubmit event and delay the usual functionality. I've created a simple demo thus you can understand it easily. Here after form submission it'll submit the form after 5 seconds, or be canceled if you hit Cancel.
const myForm = document.getElementById('myForm');
myForm.addEventListener('submit', handleSubmit);
var submitTimer;
function handleSubmit(event) {
console.log('submitTimer set');
event.preventDefault();
submitTimer = setTimeout(() => {
this.submit();
console.log('Submitted after 5 seconds');
}, 5000)
};
function cancel(){
clearTimeout(submitTimer);
console.log('Submit Canceled');
}
<form id="myForm">
<input type="text" name="name"/>
<button type="submit">Submit</button>
<button type="button" onclick="cancel()" >Cancel</button>
</form>
The setTimeout function calls a function or evaluates an expression after a specified number of milliseconds (in your case 5000). What you did in your code was just to return a boolean without creating a channel to get the value after the time has lapsed. Since this code is sort of "asynchronous" (it takes time), you can use the inbuilt Promise function to get the value. In order words, your code could be restructured to something like this:
getTheBoolValue = () => new Promise((resolve, reject) => {
setTimeout(function(){
resolve(true)
},5000)
})
getTheBoolValue().then(data => console.log(data))
So I have this piece of HTML and JavaScript
function validate() {
const tabs = document.getElementsByClassName("tab");
const input = tabs[currentTab].querySelectorAll("input[type=tel], input[type=text], input[type=time], input[type=number], input[type=email]");
const radio = tabs[currentTab].querySelectorAll("input[type=radio]");
const select = tabs[currentTab].getElementsByTagName("select");
let valid = true;
if (radio.length == 0) {
for (let i = 0; i < input.length; i++) {
if (input[i].value == "") {
valid = false;
break;
}
}
for (let i = 0; i < select.length; i++) {
if (select[i].value == "") {
valid = false;
break;
}
}
} else if (radio[0].name == "phnum" && radio[0].checked) {
if (input[0].value == "" || input[1].value == "") {
valid = false;
}
} else if (radio[1].name == "phnum" && radio[1].checked) {
if (input[0].value == "" || input[1].value == "" || input[2].value == "") {
valid = false;
}
}
if (valid) {
document.getElementById("next").className = "prevNext";
}
}
<span id="radio">
<label for="phnum1" class="radio-container">
<input type="radio" name="phnum" id="phnum1" value="1" onchange="displayPhone(this);">1 Number
<span class="radio"></span>
</label>
<label for="phnum2" class="radio-container">
<input type="radio" name="phnum" id="phnum2" value="2" onchange="displayPhone(this);">2 Numbers
<span class="radio"></span>
</label>
<label for="phnum3" class="radio-container">
<input type="radio" name="phnum" id="phnum3" value="3" onchange="displayPhone(this);">3 Numbers
<span class="radio"></span>
</label>
</span>
</p><br>
<p id="ph1" class="disable">
<label for="phone-number1">Add a Phone Number: </label><input type="tel" name="phone-number1" id="phone-number1" class="input" placeholder="Add A Phone Number" required oninput="validate();">
</p>
<p id="ph2" class="disable">
<label for="phone-number2">Add a Phone Number: </label><input type="tel" name="phone-number2" id="phone-number2" class="input" placeholder="Add A Phone Number" required onchange="validate();">
</p>
<p id="ph3" class="disable">
<label for="phone-number3">Add a Phone Number: </label><input type="tel" name="phone-number3" id="phone-number3" class="input" placeholder="Add A Phone Number" required onchange="validate();">
</p>
that handles the input added by the user to make a button clickable if all necessary data is added. the problem is when i delete inside the input with back arrow key(the one above enter) the button remains active even if the condition for its activation no longer applies.
thank you guys for your time and help i really do appreciate it. :D
One thing I see - you're setting the class name if valid == true via document.getElementById("next").className = "prevNext";.
But nowhere are you removing that class name if valid == false.
That's probably why you aren't seeing the button disappear when you empty out the fields (if I understand your problem correctly).
if (!valid) { document.getElementById("next").className = ""; } is a quick and dirty way to get what you need.
I am having issues with a code I am using to check email validity before sending it off to a database. I have a javascript code that checks the email in the following way:
See if the first email is a valid email address
See if the two email fields match
Here is the relevant parts of the form:
<form action="URLGOESHERE" method="post" name="someName" onSubmit="return validation();" id="formId">
<section class="sectionHeader">
<h2>Contact Information</h2>
<span class="important">*Required Fields</span>
</section>
<section id="contactInfo">
<fieldset>
<legend>Contact Information</legend>
<div id="contact">
<div class="inputGroupSameLine">
<label for="name" class="left"><span class="important">*</span>First Name:</label>
<input type="text" name="firstName" class="imp" size="20" maxlength="25" placeholder="John">
</div>
<div class="inputGroupSameLine">
<label for="name" class="left"><span class="important">*</span>Last Name:</label>
<input type="text" name="lastName" class="imp" size="20" maxlength="25" placeholder="Smith">
</div>
<div class="inputGroupSL">
<span class="left"><label for="org">Company/Group Name:</label></span>
<input type="text" name="org" size="30" maxlength="50" placeholder="Auburn University">
</div>
<div class="inputGroupSameLine">
<span class="left"><label for="email"><span class="important">*</span>Email:</label></span>
<input name='email' id='email' class="imp" type='text' size='45' maxlength='45' placeholder="youremail#example.com" />
</div>
<div class="inputGroupSameLine">
<span class="left"><label for="email2"><span class="important">*</span>Re-type Email:</label></span>
<input name='email2' id='email2' class="imp" type='text' size='45' maxlength='45' placeholder="youremail#example.com"/>
</div>
<div id="phoneGroup">
<span class="left"><span class="important">*</span>Phone #:</span>
<input name='phone' type='text' class="imp" id="phone" size='12' maxlength='20' placeholder="xxx-xxx-xxxx" />
</div>
<div id="extGroup">
<span class="left">Ext:</span>
<input name='ext' type='text' id="ext" size='12' maxlength='6' placeholder="xxxx" />
</div>
</div>
</fieldset>
</section>
And here is my code that runs onSubmit:
var reEMail=/^\w[\w\-\.]+\#\w[\w\-]+(\.[\w\-]+)+$/;
function validation() {
if (!checkImportant()) {
alert("Please enter information in all fields marked important.");
return false;
}
if (!checkAttendees())
return false;
if (!checkEmail($('#email'),$('#email2')))
return false;
return true;
}
function checkImportant() {
important = document.getElementsByClassName('imp');
for (i=0; i < important.length; i++) {
if($(important[i]).val() == "") {
$(important[i]).focus();
return false;
}
}
return true;
}
function checkAttendees() {
total = 0 + Number($('#numAttend').val());
parts = 0 + Number($('#8').val()) + 0 + Number($('#12').val()) + 0 + Number($('#16').val()) + 0 + Number($('#19').val()) + 0 + Number($('#26').val()) + 0 + Number($('#26').val()) + 0 + Number($('#55').val());
count = 0;
if (total != (parts)) {
alert('Please check to ensure you have entered the correct number of participants.');
count++;
if (count%2 == 0) {
$('#numAttend').focus();
return false;
}
else {
$('#8').focus();
return false;
}
}
return true;
}
function checkEmail(email,email2) {
if (goodEMail2(email)) {
if (email.val() != email2.val()) {
alert("Please check to make sure your email address is correct in both fields!");
email2.focus();
return false;
}
else return true;
}
else {
alert("Please input a valid email address");
setTimeout(function(){
$('#email').focus();
}, 100);
email.select();
return false;
}
return false;
}
function goodEMail2(field) {
return _checkIt2(reEMail, field);
}
function _checkIt2(re, field){
if (!re.test(field.val())) {
field.select();
field.focus();
return false;
}
else return true;
}
As you can see in my main if else statement of my checkEmail function I am having to use setTimeout to delay the focusing on the email field. If I take out the setTimeout, the page will not focus on the element. However, if I take out the setTimeout and change the specified element to the second email field, it works.
The only exception to this is in IE10 (to my testing in FF, Chrome, Safari, and IE10).
I don't really want to use this work around and I don't understand why I need to. Can anyone give me some ideas or answers?
Thanks!
EDIT: Can't seem to get my hack to work now. I'm not sure what it was doing before... so now focus() doesn't work at all on that particular element.
changing:
function checkImportant() {
important = document.getElementsByClassName('imp');
for (i=0; i < important.length; i++) {
if($(important[i]).val() == "") {
$(important[i]).focus();
return false;
}
}
return true;
}
to:
function checkImportant() {
important = document.getElementsByClassName('imp');
for (i=0; i < important.length; i++) {
if(important[i].value == "") { // drop the jQuery reference, not needed
important[i].focus(); // drop the jQuery reference, not needed
return false;
}
}
return true;
}
worked for me in Chrome
The validation of the checkbox doesn't work. It doesn't give any error. Could you please help me to fix it? And how can I combine errors in one alert instead of one by one?
Thanks for any help.
Html code:
<form class="contact_form" action="" method="post" name="contact_form" onsubmit="returnonFormSubmit(this)">
<li>
<label for="First Name">First Name:</label>
<input type="text" name="visitor_name" /><br />
</li>
<li>
<label for="condition">I agree with the terms and conditions.</label>
<input type="checkbox" name="lan" /><br />
</li>
<li>
<label for="Male">Male:</label>
<input type="radio" name="gender" value="m" /> Female:<input type="radio" name="gender" value="f" /><br />
</li>
<li>
<label for="National Rating">National Rating:</label>
<select name="make">
<option selected>-- SELECT --</option>
<option> Below 1200 </option>
<option> 1200 - 1500 </option>
<option> 1500 - 1800 </option>
<option> 1800 - 2100 </option>
<option> Above 2100 </option>
</select><br />
</li>
<li>
<button class="submit" type="submit">Submit</button>
</li>
<div id="error_message" style="color:#ff0000;"></div>
javascript code:
function onFormSubmit(form_element)
{
var checked = 0;
var letters = /^[a-zA-Z]+$/;
if (form_element.visitor_name.value.match(letters))
{
true;
}
else
{
alert("Please enter a valid first name. For example; John.");
false;
}
if (form_element.lan.checked == false)
{
alert("Please accept the terms and conditions");
false;
}
if (form_element.gender[0].checked == false && form_element.gender[1].checked == false)
{
alert("Please select a gender.");
false;
}
if (form_element.make.selectedIndex == 0)
{
alert("Please select your rating interval.");
form_element.make.focus();
false;
}
return true;
}
You should concatenate the error messages in a variable.
function onFormSubmit(form_element)
{
var checked = 0;
var letters = /^[a-zA-Z]+$/;
var errorMessage = "";
if (!form_element.visitor_name.value.match(letters))
{
errorMessage += "Please enter a valid first name. For example; John.\n";
}
if (form_element.lan.checked == false)
{
errorMessage += "Please accept the terms and conditions\n";
}
if (errorMessage != "")
{
alert(errorMessage);
return false;
}
return true;
}
You have a typo in onsubmit="returnonFormSubmit(this)". It should be
onsubmit="return onFormSubmit(this)"
Running this with a console open would give you a valuable error/warning. Try Chrome's Developer Tools, Firefox' Firebug or similar.
To combine the errors into one, you could start out with an empty string msg = '' and append to it if there is an error. Then at the bottom of your function, alert(msg) and return false if it is non-empty, otherwise return true.
After fixing typo in returnonFormSubmit(this) it works in Chrome and Firefox.
(BTW: you forget returns)
To combine alerts I would use an array.
Example:
function onFormSubmit(form_element)
{
var checked = 0;
var letters = /^[a-zA-Z]+$/;
var alerts = new Array();
if (!form_element.visitor_name.value.match(letters))
alerts.push("Please enter a valid first name. For example; John.");
if (!form_element.lan.checked)
alerts.push("Please accept the terms and conditions");
if (alerts.length == 0) {
return true;
}
alert(alerts.join("\n"));
return false;
}