So for the past few days I've been struggling on how to pas information from my product page to an order form. I'm to the point where I can't figure out what to do with the coding that I've done to make the web pages.
This is all of my coding for three pages
Home page:
body{
background-color:#56A5EC;
}
div.banner{
text-align:center;
color:#ED9C55;
font-size:45px;
width:750px;
height:50px;
position:relative;
top:0px;
margin-left:auto;
margin-right:auto;
border:1px solid black;
}
div.nav{
font-size:25px;
color:#56A5EC;
background-color:#ED9C55;
width:750px;
height:30px;
margin-left:auto;
margin-right:auto;
position:relative;
top:3px;
border:1px solid black;
}
div.main{
position:relative;
top:6px;
width:750px;
height:600px;
margin-left:auto;
margin-right:auto;
position:relative;
border:1px solid black;
background-color:white;
}
div.footer{
background-color:#ED9C55;
font-size: 20px;
height:180px;
width:752px;
margin-left:auto;
margin-right:auto;
position:relative;
bottom:8px;
z-index:1;
color:white;
}
p.welcome{
text-align:center;
margin-left:auto;
margin-right:auto;
font-size:25px;
color:blac
<div class="wrapper">
<div class="banner">Welcome to Electro-Market</div>
<div class="nav">Product page</div>
<div class=""main>
<p class="welcome">
Welcome to my store where we sell electronic devices that you may enjoy. Here we are committed to satisfying your needs.
</p>
</div>
<div class="footer">
If you need to contact about stock avaliablity please don't hesitate to call (918)999-0987.
</div>
</div>
Product page:
var products = [];
var url_string = document.location.search.substring(1,document.location.search.length);
if( url_string.length > 0 ) {
var parameters = url_string.split('&');
for(var x = 0 ; x < parameters.length ; x++ ) {
products.push(parameters[x].split('='));
}
console.log(products);
} else {
console.log("no parameters");
}
window.onload = function( ) {
var form = document.getElementById("order_form");
form.onsubmit = function( ) {
var controls = document.getElementsByTagName("input");
for( var x = 0 ; x < controls.length ; x++ ){
if( controls[x].type == "checkbox" && controls[x].checked ) {
return true;
}
}
alert("You must select one product at least");
return false;
}
}
body{
background-color:#56A5EC;
}
<form action="lab07_order_form.html" method="get" id="order_form">
<h2>Lenovo Computer - $650.00</h2>
<div>
<input type="checkbox" name="Product1" value="" id="Product1"/>
<label for="product-1"><img src="Lenovo-pc.jpg" alt="Computer" style="width:225px;height:200px;"> Thi computer has many features built into it such as Intel i5 core processor 8GB ram and 1 TB of memory.</label>
</div>
<h2>Nintendo 64 - $50.00</h2>
<div>
<input type="checkbox" name="Product2" value="" id="Product2"/>
<label for="product-2"><img src="Nintendo-64.jpg" alt="Nintendo" style="width:225px;height:200px;"> A console from the 90's that many kids loved to play at a friends house and an all around family activity. Though cartridges are sold separately and come in serveral different games.</label>
</div>
<h2>Playstation 2 - $150.00</h2>
<div>
<input type="checkbox" name="Product3" value="" id="Product3"/>
<label for="product-3"><img src="playstation.jpg" alt="ps2" style="width:225px;height:200px;"> The Playstation 2 is a more modern console that is one of our highly anticipated consoles.</label>
</div>
<h2>Xbox - $125.00</h2>
<div>
<input type="checkbox" name="Product4" value="" id="Product4"/>
<label for="product-4"><img src="xbox.jpg" alt="xbox" style="width:225px;height:200px;">Xbox is made by microsoft and has one of the most iconic games ever played Halo and are in limited supply</label>
</div>
<div>
<input type="submit" value="Purchase item's"/>
</div>
</form>
<form action="lab_07.html" method="get" id="lab_07">
<input type="submit" value="Back"/>
</form>
Form page:
var ids = ['first_name', 'last_name','street_address','city','state','zip', 'Billing_address', 'Billing_city', 'Billing_state', 'Billing_zip', 'Card_type', 'Card_number', 'Card_date'];
function validate( ){
var errors = new Array();
for(var x = 0 ; x <document.forms[0].elements.length ; x++ ) {
if(document.forms[0].elements[ x ].type == "text"){
if(document.forms[0].elements[ x ].value == ""){
errors.push("The " + document.forms[0].elements[x].name + " field cannot be blank\n");
document.forms[0].elements[x].className = "in_error";
} else {
document.forms[0].elements[x].className = "no_error";
}
}
if( document.forms[0].elements[x].type == "select-one"){
if(document.forms[0].elements[x].selectIndex == 0){
errors.push("The " + document.forms[0].elements[x].name + " field cannot be blank\n");
document.forms[0].elements[x].className = "in_error";
} else {
document.forms[0].elements[x].className = "no_error";
}
}
}
if(errors.length == 0 ){
return true;
} else {
clear_errors( );
show_errors( errors );
return false;
}
}
var products = [];
var url_string = document.location.search.substring(1,document.location.search.length);
if( url_string.length > 0 ) {
var parameters = url_string.split('&');
for(var x = 0 ; x < parameters.length ; x++ ) {
products.push(parameters[x].split('='));
}
console.log(products);
} else {
console.log("no parameters");
}
function FillBilling(z){
if(z.billingtoo.checked == true) {
z.Billing_address.value = z.street_address.value;
z.Billing_city.value = z.city.value;
z.Billing_state.value = z.state.value;
z.Billing_zip.value = z.zip.value;
}
if(z.billingtoo.checked == false){
z.Billing_address.value = '';
z.Billing_city.value = '';
z.Billing_state.value = '';
z.Billing_zip.value = '';
}
}
function clear_errors(){
var div = document.getElementById( "errors" );
while(div.hasChildNodes()){
div.removeChild(div.firstChild);
}
}
function show_errors( errors ) {
var div = document.getElementById( "errors" );
for( var x = 0 ; x < errors.length ; x++ ) {
var error = document.createTextNode( errors[ x ]);
var p = document.createElement( "p" );
p.appendChild(error);
div.appendChild(p);
}
}
window.onload = function() {
document.forms[ 0 ].onsubmit = validate;
for( var x = 0 ; x < ids.length ; x++ ) {
var element = document.getElementById(ids[x]);
element.onfocus = function(){
console.log(this.id + " has been focused");
this.className = "element_focused";
document.getElementById(this.id + "_label").className = "element_focused";
}
element.onblur = function( ) {
console.log(this.id + " has been blurred");
this.className = "";
document.getElementById(this.id + "_label").className = "";
}
}
var products_div = document.getElementById("products");
var order_form = document.getElementById("order_form");
for( var x = 0 ; x < products.length ; x++ ) {
//create colored background div's
var div = document.createElement("div");
div.style.backgroundColor = products[x][1];
products_div.appendChild(div);
//create form fields
var input = document.createElement("input");
input.type = "hidden";
input.name = products[x][0];
input.value = products[x][1];
order_form.appendChild(input);
}
}
#errors {
color: #F00;
}
.in_error{
background-color: #F00;
}
.no_error{
background-color: #FFFFFF;
}
input.element_focused, select.element_focused {
border: 5px solid #F00;
}
label.element_focused {
color: #F00;
}
<h1>Products</h1>
<div id="products"></div>
<div id="errors"></div>
<form method="get" action="https://suchnull.com/examples/echo">
<p>
<label for="first_name" id="first_name_label">First Name:</label>
<input type="text" name="first name" value="" id="first_name"/>
</p>
<p>
<label for="last_name" id="last_name_label">Last Name:</label>
<input type="text" name="last name" value="" id="last_name"/>
</p>
<p>
<label for="street_address" id="street_address_label">Shipping Address:</label>
<input type="text" name="street address" value="" id="street_address"/>
<input type="checkbox" onclick="FillBilling(this.form)" name="billingtoo"/>
</p>
<p>
<label for="city" id="city_label">Shipping City:</label>
<input type="text" name="city" value="" id="city"/>
</p>
<p>
<label for="state" id="state_label">Shipping State:</label>
<input type="text" name="state" value="" id="state"/>
</p>
<p>
<label for="zip" id="zip_label">Shipping Zip:</label>
<input type="text" name="zip" value="" id="zip"/>
</p>
<p>
<label for="Billing_address" id="Billing_address_label">Billing address:</label>
<input type="text" name="Billing address" value="" id="Billing_address"/>
</p>
<p>
<label for="Billing_city" id="Billing_city_label">Billing City:</label>
<input type="text" name="Billing city" value="" id="Billing_city"/>
</p>
<p>
<label for="Billing_state" id="Billing_state_label">Billing State:</label>
<input type="text" name="Billing state" value="" id="Billing_state"/>
</p>
<p>
<label for="Billing_zip" id="Billing_zip_label">Billing Zip:</label>
<input type="text" name="Billing zip" value="" id="Billing_zip"/>
</p>
<p>
<label for="Card_type" id="Card_type_label">Credit Card Type:</label>
<input type="text" name="Card type" value="" id="Card_type"/>
</p>
<p>
<label for="Card_number" id="Card_number_label">Credit Card Number:</label>
<input type="text" name="Card number" value="" id="Card_number"/>
</p>
<p>
<label for="Card_date" id="Card_date_label">Credit Card Expiration Date:</label>
<input type="text" name="Card date" value="" id="Card_date"/>
</p>
<p>
<form method="get" action="https://suchnull.com/examples/echo">
<input type="checkbox" name="checkbox" value="check" /> I've completed the information
<input type="submit" name="submit" value="submit" onclick="if(!this.form.checkbox.checked){alert('You must agree to the terms first.');return false}" />
</form>
</p>
</form>
Can anyone tell me what I'm doing wrong and help me understand how to transfer the image of the product, price, and name because I'm completely lost on how to do this.
Related
my script
<script>
function hii(Name,Mobile){
let Count=0;
if(Name=="" || Name==null){
document.getElementById('nameerror').style.display='block';
document.getElementById('nameerror').innerHTML='Please Enter Student Name';
Count++;
}
if(Mobile=="" || Mobile==null){
document.getElementById('mobileerror').style.display='block';
document.getElementById('mobileerror').innerHTML='Please Enter Student Mobile';
Count++;
}
if(Count>0){
alert(Count);
return false;
}
}
</script>
Html
<form action="addstudent.php" method="POST" onsubmit="hii(
document.getElementById('name').value,
document.getElementById('mobile').value
)">
<input type="text" name='name' id="name" placeholder="Enter Student Name"><br><br>
<label for="" id="nameerror" style="display: none;color:red;font-size:small;"></label>
<input type="number" name='mobile' id='mobile' placeholder="Enter Mobile Number"><br><br>
<label for="" id="mobileerror" style="display: none;color:red;font-size:small;"></label>
<input type="submit" value="add">
</form>
im getting count as 2 via alert after submitting form with no data which means there are no errors in my html and javascript code and i cant find any flashing errors in console
What you need is to pass an event to the submit function, and use event.preventDefault() to stop the submission.
function hii(event, Name, Mobile) {
let Count = 0;
if (Name == "" || Name == null) {
document.getElementById("nameerror").style.display = "block";
document.getElementById("nameerror").innerHTML =
"Please Enter Student Name";
Count++;
}
if (Mobile == "" || Mobile == null) {
document.getElementById("mobileerror").style.display = "block";
document.getElementById("mobileerror").innerHTML =
"Please Enter Student Mobile";
Count++;
}
if (Count > 0) {
event.preventDefault();
alert(Count);
}
}
<form
action="addstudent.php"
method="POST"
onsubmit="hii(
event,
document.getElementById('name').value,
document.getElementById('mobile').value
)"
>
<input
type="text"
name="name"
id="name"
placeholder="Enter Student Name"
/><br /><br />
<label
for=""
id="nameerror"
style="display: none; color: red; font-size: small"
></label>
<input
type="number"
name="mobile"
id="mobile"
placeholder="Enter Mobile Number"
/><br /><br />
<label
for=""
id="mobileerror"
style="display: none; color: red; font-size: small"
></label>
<input type="submit" value="add" />
</form>
A better solution is to use addEventListener()
document.querySelector("#form1").addEventListener("submit", hii);
function hii(event) {
const Name = document.querySelector("#name").value;
const Mobile = document.querySelector("#mobile").value;
let Count = 0;
if (Name == "" || Name == null) {
document.getElementById("nameerror").style.display = "block";
document.getElementById("nameerror").innerHTML =
"Please Enter Student Name";
Count++;
}
if (Mobile == "" || Mobile == null) {
document.getElementById("mobileerror").style.display = "block";
document.getElementById("mobileerror").innerHTML =
"Please Enter Student Mobile";
Count++;
}
if (Count > 0) {
event.preventDefault();
alert(Count);
}
}
<form
id="form1"
action="addstudent.php"
method="POST"
>
<input
type="text"
name="name"
id="name"
placeholder="Enter Student Name"
/><br /><br />
<label
for=""
id="nameerror"
style="display: none; color: red; font-size: small"
></label>
<input
type="number"
name="mobile"
id="mobile"
placeholder="Enter Mobile Number"
/><br /><br />
<label
for=""
id="mobileerror"
style="display: none; color: red; font-size: small"
></label>
<input type="submit" value="add" />
</form>
You have to return the value in the handler
<form action="addstudent.php" method="POST" onsubmit="return hii(
document.getElementById('name').value,
document.getElementById('mobile').value
)">
But better yet is to keep it all together in your script
<form action="addstudent.php" method="POST">
<!-- remove the onsubmit here -->
<input type="submit" value="add">
<!-- we'll put the listener here -->
Then, your script
document.querySelector('input[type="submit"]').addEventListener('click', function(e) {
e.preventDefault();
let Count = 0;
let Name = document.getElementById('name').value;
let Mobile = document.getElementById('mobile').value
if (Name == "" || Name == null) {
document.getElementById('nameerror').style.display = 'block';
document.getElementById('nameerror').innerHTML = 'Please Enter Student Name';
Count++;
}
if (Mobile == "" || Mobile == null) {
document.getElementById('mobileerror').style.display = 'block';
document.getElementById('mobileerror').innerHTML = 'Please Enter Student Mobile';
Count++;
}
if (Count > 0) {
alert(Count);
return false;
}
document.querySelector('form').submit()
})
I am playing around with some code from the internet to try and create a mock dog walking appointment scheduling application. So far I have my multi-step form which works as should, however I have been trying to move on to starting the submit handling, and realised that as the 'next' button is changed to 'submit' (innerHTML), in the JavaScript, I am not sure where to put the onSubmit() handling functionality..
The challenge is that I am not allowed to use any server side programming, only HTML, CSS, JS and jQuery. Handling the form seems straight-forward enough but I am unsure where to implement the onSubmit() function.
Please go easy on me, it is a university challenge and JS is not my strong point, I have tried looking online but the only suggestions I have are for putting the onSubmit into the button itself, which would be the obvious option but as it's a multi-step form the submit button is not coded into the HTML.
https://codepen.io/caitlinmooneyx/pen/PoGqMaG
HTML
<form id="regForm" name="regForm" action="" class="col-sm-6">
<div class="tab">
<h3>Book your dog walk now</h3>
<!-- BOOKING FORM -->
<div class="row">
<p>Tell us about yourself first..</p>
</div>
<div class="row">
<input type="text" id="fname" placeholder="First Name" name="fname" required>
<input type="text" id="lname" placeholder="Last Name" name="lname" required>
</div>
<div class="row">
<input type="number" id="number" placeholder="Contact Number" name="Number" required>
<input type="email" id="email" placeholder="Email Address" name="email">
</div>
<div class="row">
<p>When should we pick your dog up?</p>
</div>
<div class="row">
<input type="date" id="sdate" class="datepicker" name="sdate" onchange="checkStartDate()" required>
<select name="stime" id="stime" required>
<option value="" selected disabled hidden>Choose a time</option>
<option value="nine">9:00</option>
<option value="hnine">9:30</option>
<option value="ten">10:00</option>
<option value="hten">10:30</option>
<option value="eleven">11:00</option>
<option value="heleven">11:30</option>
<option value="twelve">12:00</option>
<option value="htwelve">12:30</option>
<option value="one">13:00</option>
<option value="hone">13:30</option>
<option value="two">14:00</option>
<option value="htwo">14:30</option>
<option value="three">15:00</option>
</select>
<select name="duration" id="duration" required>
<option value="" selected disabled hidden>Duration</option>
<option value="halfhour">30 mins</option>
<option value="onehour">1 hour</option>
<option value="onehalfhour">1.5 hours</option>
<option value="twohour">2 hours</option>
</select>
</div>
<div class="row">
<p>Where should we pick up/drop off your dog?</p>
</div>
<div class="row">
<div id="locationField">
<input
id="autocomplete"
placeholder="Start typing your address..."
onFocus="geolocate()"
type="text"
required
/>
</div>
</div>
</div>
<div class="tab">
<h3>Now tell us more about your dog..</h3>
<div class="row">
<input type="text" id="dogname" placeholder="Dog Name" name="dogname" required>
</div>
<div class="row">
<p>What breed are they?</p>
</div>
<div class="row">
<select class="breeds"></select>
</div>
<div class="row">
<p>Their favourite places?</p>
</div>
<div class="row">
<input type="checkbox" id="parks" name="parks" value="Parks">
<label for="parks"> Parks</label><br>
<input type="checkbox" id="forests" name="forests" value="Forests">
<label for="forests"> Forests</label><br>
<input type="checkbox" id="beaches" name="beaches" value="Beaches">
<label for="beaches"> Beaches</label>
</div>
<div class="row">
<p>Anything else we should know? (Favourite toys, places to avoid etc)</p>
</div>
<div class="row">
<textarea></textarea>
</div>
</div>
<div style="overflow:auto;">
<div style="float:right;">
<button type="button" id="prevBtn" onclick="nextPrev(-1)">Previous</button>
<button type="button" id="nextBtn" onclick="nextPrev(1)">Next</button>
</div>
</div>
<div style="text-align:center;margin-top:40px;">
<span class="step"></span>
<span class="step"></span>
</div>
</form>
CSS
form p {
margin: 1em 0 .5em 1em;
}
form {
background-color: #fafafa;
padding: 1.5em;
/*margin-right: 6em;*/
}
input, select, textarea {
margin: 1em;
padding: .5em;
width: 45%;
font-size: 17px;
border: 1px solid #aaa;
}
input[type="checkbox"] {
width: auto;
margin: .5em 1em 0 1em;
}
input[type="date"] {
color: #aaa!important;
}
#locationField > input {
width: 290%!important;
}
input.invalid {
background-color: #ffdddd;
}
.tab {
display: none;
}
.step {
height: 15px;
width: 15px;
margin: 0 2px;
background-color: #bbbbbb;
border: none;
border-radius: 50%;
display: inline-block;
opacity: 0.5;
}
.step.active {
opacity: 1;
background-color: #fac123;
}
JS
// ~~~ tab functionality
var currentTab = 0; // current tab is set to be the first tab (0)
showTab(currentTab); // display the current tab
function showTab(n) {
var x = document.getElementsByClassName("tab");
x[n].style.display = "block";
if (n == 0) {
document.getElementById("prevBtn").style.display = "none";
} else {
document.getElementById("prevBtn").style.display = "inline";
}
if (n == (x.length - 1)) {
document.getElementById("nextBtn").innerHTML = "Submit";
} else {
document.getElementById("nextBtn").innerHTML = "Next";
}
fixStepIndicator(n)
}
function nextPrev(n) {
var x = document.getElementsByClassName("tab");
if (n == 1 && !validateForm()) return false;
x[currentTab].style.display = "none";
currentTab = currentTab + n;
if (currentTab >= x.length) {
//...the form gets submitted:
document.getElementById("regForm").submit();
return false;
}
showTab(currentTab);
}
function validateForm() {
var x, y, i, s, valid = true;
x = document.getElementsByClassName("tab");
y = x[currentTab].getElementsByTagName("input");
s = x[currentTab].getElementsByTagName("select");
for (i = 0; i < y.length; i++) {
if (y[i].value == "") {
y[i].className += " invalid";
valid = false;
}
}
for (i = 0; i < s.length; i++) {
if (s[i].value == "") {
s[i].className += " invalid";
valid = false;
}
}
if (valid) {
document.getElementsByClassName("step")[currentTab].className += " finish";
}
return valid; // return the valid status
}
function fixStepIndicator(n) {
var i, x = document.getElementsByClassName("step");
for (i = 0; i < x.length; i++) {
x[i].className = x[i].className.replace(" active", "");
}
x[n].className += " active";
}
// ~~~ dog breed selector
const BREEDS_URL = 'https://dog.ceo/api/breeds/list/all';
const select = document.querySelector('.breeds');
fetch(BREEDS_URL)
.then(res => {
return res.json();
})
.then(data => {
const breedsObject = data.message;
const breedsArray = Object.keys(breedsObject);
for (let i = 0; i < breedsArray.length; i++) {
const option = document.createElement('option');
option.value = breedsArray[i];
option.innerText = breedsArray[i];
select.appendChild(option);
}
console.log(breedsArray);
});
// ~~~ basic form validation
// ~~~ date validation
function checkStartDate() {
var startDate = document.getElementById('sdate').value;
var selectedStartDate = new Date(startDate);
var now = new Date();
if (selectedStartDate < now) {
alert("Start date must be in the future");
$("#sdate").addClass("invalid");
}
}
One solution could be to have a submit button that you hide by default (on the first tab) and show once you go to the second (or last if you add more). This way you won't have to change the innerHTML on any element and just toggle a class. Something like that could look like:
<form id="regForm" name="regForm" action="[NEED ACTION]" class="col-sm-6">
...
<div style="overflow:auto;">
<div style="float:right;">
<button type="button" id="prevBtn" click="nextPrev(-1)">Previous</button>
<button type="button" id="nextBtn" onclick="nextPrev(1)">Next</button>
<submit type="submit" class="hide" value="Submit" />
</div>
</div>
</form>
function showTab(n) {
var x = document.getElementsByClassName("tab");
x[n].style.display = "block";
if (n == 0) {
document.getElementById("prevBtn").style.display = "none";
} else {
document.getElementById("prevBtn").style.display = "inline";
}
if (n == (x.length - 1)) {
document.getElementById("nextBtn").classList.add('hide');
document.getElementById("submitBtn").classList.remove('hide');
} else {
document.getElementById("nextBtn").classList.remove('hide');
document.getElementById("submitBtn").classList.add('hide');
}
fixStepIndicator(n)
}
For this to work you will need to fill in the action property for the form.
Another way you could do this without adding an extra element would be to change the onClick action for the next/submit button.
function showTab(n) {
var x = document.getElementsByClassName("tab");
var nextSubmitBtn = document.getElementById("nextBtn");
x[n].style.display = "block";
if (n == 0) {
document.getElementById("prevBtn").style.display = "none";
} else {
document.getElementById("prevBtn").style.display = "inline";
}
if (n == (x.length - 1)) {
nextSubmitBtn.textContent = "Submit";
nextSubmitBtn.onClick = someSubmitFunc;
} else {
nextSubmitBtn.textContent = "Next";
nextSubmitBtn.onClick = function () { nextPrev(1); };
}
fixStepIndicator(n)
}
This would allow you to keep the same HTML and handle the solution via JS. If you do this remember to keep the current onClick property on the "next" button as that will be the initial function ran (when you first click "next")
A couple tips and notes:
If you are only changing the text of an element (like from "next" to "submit") it would be best to use a function that only changes the text:
// Pure JS
element.textContnet = 'some text';
// jQuery
$element.text('some other text');
this will help prevent possible bugs (and potentially security risk) that can come from innerHTML.
You say you are using jQuery but it is only used in one line in the JS code presented. If that is the only line using jQuery library you could easily replace it and not include the library saving on you site size.
// jQuery way to add class (line 111)
$("#sdate").addClass("invalid");
// Pure JS equivalent
document.getElementById('sdate').classList.add('invalid');
Both will get the job done (add a class) and if you prefer to use jQuery more power to you but if that is the only place you use it then this could be an alternative.
<!DOCTYPE html>
<html><head><title>CT Traders</title>
<style>
fieldset {width:40%; margin:0px 0px 10px 1%;}
legend {padding:2px; text-indent:5px;}
h2, p {margin-left: 1%;}
input[type="submit"], input[type="reset"]
{display:inline; float:none;}
</style>
<script>
//suggested logic for the validateInput() function
function validateInputs()
{
//check payment method
var methodChecked = false;
for (var i=0; i <document.frmCustOrders.class.length;i++)
{
if (document.frmCustOrders.class[i].checked ==true)
{
classChecked = true;
vClass = document.frmCustOrders.class[i].value;
}
}
//check customer index value
var customerIndex = document.getElementById("customer").value;
//retrieve order quantity
var qty = document.getElementById("qty").value;
//validate form data
if (customerIndex == -1) //validate customer
{
alert("Please select a customer.")
return false;
}
else if () //validate qty
{
}
else if (fsClassChecked == false) //validate payment method
{
alert("Please select a payment method.")
return false;
}
else //output
{
orderEntries = customer+ "\n"+ qty+ "\n"+vClass;
alert(orderEntries);
return false;
}
}
</script>
</head>
<body>
<h2>Customer Order</h2>
<form name="frmCustOrders" id="frmCustOrders"
onsubmit="return validateInputs();" action="">
<fieldset id="fsCustomer">
<legend>Customer List</legend>
<select name="customer" id="customer" size="3">
<option>107 Paula Harris</option>
<option>232 Mitch Edwards</option>
<option>229 BTC</option>
</select>
</fieldset>
<p>
<label for="qty">Order Quantity: </label>
<input type="text" name="qty" id="qty" />
</p>
<fieldset id="fsClass">
<legend>Payment Method</legend>
<input type="radio" name="method" id="check" value="check" />
Check<br />
<input type="radio" name="method" id="creditCard" value="credit card" />
Credit Card<br />
<input type="radio" name="method" id="debitCard" value="debit card" />
Debit Card
</fieldset>
<p> <input type="submit" value="Submit" />
<input type="reset" value="Reset" /></p>
</form>
</body>
</html>
I'm having issues getting an output box that retrieves the selections on the form.
Also, in one of my if statements I'm assigned to check if the value is between 1 and 999 but I'm drawing a total blank on this. I'm new to coding (Javascript) and this is my first class. Any help with getting this to work would be greatly appreciated.
There are some issues with your code
Redundant else if ()
fsClassChecked variable not declared.
Redundant class when iterate elements document.frmCustOrders.class
Use wrong variable customer should be customerIndex
Wrong condition (customerIndex == -1) change to (customerIndex == "")
//suggested logic for the validateInput() function
function validateInputs()
{
//check payment method
var methodChecked = false;
var fsClassChecked = false;
for (var i=0; i <document.frmCustOrders.length;i++)
{
if (document.frmCustOrders[i].checked ==true)
{
fsClassChecked = true;
vClass = document.frmCustOrders[i].value;
}
}
//check customer index value
var customerIndex = document.getElementById("customer").value;
//retrieve order quantity
var qty = document.getElementById("qty").value;
//validate form data
if (customerIndex == "") //validate customer
{
alert("Please select a customer.")
return false;
}
else if(qty == "" || qty < 1 || qty > 999){
alert("Please enter qty 1-999.")
return false;
}
else if (fsClassChecked == false) //validate payment method
{
alert("Please select a payment method.")
return false;
}
else //output
{
orderEntries = customerIndex + "\n"+ qty+ "\n"+vClass;
alert(orderEntries);
return false;
}
return false;
}
<!DOCTYPE html>
<html><head><title>CT Traders</title>
<style>
fieldset {width:40%; margin:0px 0px 10px 1%;}
legend {padding:2px; text-indent:5px;}
h2, p {margin-left: 1%;}
input[type="submit"], input[type="reset"]
{display:inline; float:none;}
</style>
<script>
</script>
</head>
<body>
<h2>Customer Order</h2>
<form name="frmCustOrders" id="frmCustOrders"
onsubmit="return validateInputs();" action="#">
<fieldset id="fsCustomer">
<legend>Customer List</legend>
<select name="customer" id="customer" size="3">
<option>107 Paula Harris</option>
<option>232 Mitch Edwards</option>
<option>229 BTC</option>
</select>
</fieldset>
<p>
<label for="qty">Order Quantity: </label>
<input type="text" name="qty" id="qty" />
</p>
<fieldset id="fsClass">
<legend>Payment Method</legend>
<input type="radio" name="method" id="check" value="check" />
Check<br />
<input type="radio" name="method" id="creditCard" value="credit card" />
Credit Card<br />
<input type="radio" name="method" id="debitCard" value="debit card" />
Debit Card
</fieldset>
<p> <input type="submit" value="Submit" />
<input type="reset" value="Reset" /></p>
</form>
</body>
</html>
Still weeks into Javascript class it was a short fast pace class and I have this final project that has three class of orders with 3 options to chose from. All are radio type with amounts. There is no quantities listed nor is there tax or subtotal. The Total box should have a running balance and will clear when the Clear button is clicked.
This is what I have so far:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Javascript - Unit 2 Summary</title>
<link href="unit2-summary.css" rel="stylesheet" type="text/css"></link>
<script type="text/javascript">
/*function swap()
{
var left = $('#leftWrapper').html();
var right = $('#rightWrapper').html();
$('#leftwrapper').html(left);
$('#rightWrapper').html(right);
return false;
}*/
function doClear()
{
document.computerForm.totalSystemPrice.value = "";
document.ComputerForm.yourName.value = "";
document.ComputerForm.yourAddress.value = "";
document.ComputerForm.yourAddress2.value = "";
document.ComputerForm.yourCityStateZip.value = "";
document.ComputerForm.yourPhone.value = "";
document.ComputerForm.yourEmail.value = "";
document.ComputerForm.computerCase[0].checked = false;
document.ComputerForm.computerCase[1].checked = false;
document.ComputerForm.computerCase[2].checked = false;
document.ComputerForm.computerMonitor[0].checked = false;
document.ComputerForm.computerMonitor[1].checked = false;
document.ComputerForm.computerMonitor[2].checked = false;
document.ComputerForm.computerPrinter[0].checked = false;
document.ComputerForm.computerPrinter[1].checked = false;
document.ComputerForm.computerPrinter[2].checked = false;
return;
}
function doSubmit()
{
if (validateText() == false)
{
alert("Required Data Missing - Please Complete");
return;
}
if (validateRadio() == false)
{
alert("Required Order Data Missing - Please Complete");
return;
}
alert("Your Order has been placed.");
return;
}
function validateText()
{
var yourName = document.ComputerForm.yourName.value;
if (yourName.length == 0) return false;
var yourAddress = document.computerForm.yourAddress.value;
if (yourAddress.length == 0) return false;
var yourCityStateZip = document.ComputerForm.yourCityStateZip.value;
if (yourCityStateZip.length == 0) return false;
var yourPhone = document.ComputerForm.yourPhone.value;
if (yourPhone == 0) return false;
var yourEmail = document.ComputerForm.yourEmail.value;
if (yourEmail == 0) return false;
return true;
}
function validateRadio()
{
if (document.ComputerForm.computerCase[0].checked) return true;
if (document.ComputerForm.computerCase[1].checked) return true;
if (document.ComputerForm.computerCase[2].checked) return true;
if (document.ComputerForm.computerMonitor[0].checked) return true;
if (document.ComputerForm.computerMonitor[1].checked) return true;
if (document.ComputerForm.computerMonitor[2].checked) return true;
if (document.ComputerForm.computerPrinter[0].checked) return true;
if (document.ComputerForm.computerPrinter[1].checked) return true;
if (document.ComputerForm.computerPrinter[2].checked) return true;
}
function getTotal()
{
var computerPrice()
document.getElementById('totalPrice').value.innerHTML = "Total Computer Price $"
}
function startup()
{
var imgArray = new Array(3);
var index = 0;
imgArray[0] = new Image;
imgArray[0].src = "ComputerCase.jpg";
imgArray[1] = new Image;
imgArray[1].src = "ComputerMonitor.jpg";
imgArray[2] = new Image;
imgArray[2].src = "ComputerPrinter.jpg";
return;
}
</script>
</head>
<body>
<form name="ComputerForm">
<h1 align="center">Comupter System Order Form</h1>
<div id="container" font="courier" size="10">
<div id="left"><div id ="leftWrapper" class="wrapper">
<p><p></p>
<div class="gallery">
<a target="_blank" href="ComputerCase.jpg">
<img src="ComputerCase.jpg">
</a>
</div>
<h4>Computer Case Style:</h4>
<input name="computerCase" type="radio" onClick="calculateTotal()" />Desktop Case ($500.00)<br />
<input name="computerCase" type="radio" onClick="calculateTotal()" />Mini-Tower Case ($600.00)<br />
<input name="computerCase" type="radio" onClick="calculateTotal()" />Full Tower Case ($700.00)<br />
<p></p>
<div class="gallery">
<a target="_blank" href="ComputerMonitor.jpg">
<img src="ComputerMonitor.jpg">
</a>
</div>
<h4>Computer Monitors</h4>
<input name="computerMonitor" type="radio" onClick="calculateTotal()" />17" LCD Flat Screen ($250.00)<br />
<input name="computerMonitor" type="radio" onClick="calculateTotal()" />19" LCD Flat Screen ($300.00)<br />
<input name="computerMonitor" type="radio" onClick="calculateTotal()" />21" LCD Flat Screen ($350.00)<br />
<p></p>
<div class="gallery">
<a target="_blank" href="ComputerPrinter.jpg">
<img src="ComputerPrinter.jpg"></a>
</a>
</div>
<h4>Computer Printers</h4>
<input name="computerPrinter" type="radio" onClick="calculateTotal()" />Inkjet Printer ($100.00)<br />
<input name="computerPrinter" type="radio" onClick="calculateTotal()" />Laser Printer ($250.00)<br />
<input name="computerPrinter" type="radio" onClick="calculateTotal()" />Color Laser Printer ($350.00)<br />
</p><p></p>
</div>
</div>
<div id="right"><div id="rightWrapper" class="wrapper">
<br><br>
<p>Total System Price: $
<input name="totalSystemPrice" size="14px" type="text" id="totalPrice" class="totalPrice" readonly>
</p>
<br><br>
<hr />
<p></p><p></p><p></p>
Name: <input name="yourName" size="50" type="text"><br />
Address: <input name="yourAddress" size="50" type="text"><br />
<input name="yourAddress2" size="50" type="text"><br />
City, State, Zip: <input name="yourCityStateZip" size="50" type="text"><br />
Phone Number: <input name="yourPhone" size="50" type="text"><br />
Email Address: <input name="yourEmail" size="50" type="text"></p>
</p>
<hr />
<br><br><br>
<div align="center">
<input type="button" id="submit" value="Submit Order" onClick="doSubmit()">
<input type="button" id="reset" value="Clear Values" onClick="doClear()">
</div>
<br />
</div></div>
</form>
</body>
</html>
The CSS page is so far:
body
{
color:black;
}
p
{
color:black;
font-size:12px;
font-family: Constantia, Aldhabi, Book Antiqua;
}
h1
{
color:blue;
font-weight:bold;
font-family:"Book Antiqua";
}
h4
{
color:blue;
font-weight:bold;
font-family:"Book Antiqua", Arial;
}
.gallery
{
float:right;
}
div.gallery.hover
{
border: 1px solid orange;
}
div.gallery.img
{
width:110px;
height: 110px;
}
#TotalSystemPrice
{
}
#container
{
display: table;
table-layout: fixed;
width:90%;
height:100%;
border: 1px solid black;
padding: 3px;
}
#left, #right
{
display: table-cell;
}
#left
{
width: 50%;
height: 100%;
background: white;
border: 1px solid blue;
margin:3px 2px;
}
#right
{
width: 50%;
height: 100%;
background-color:ivory;
border: 1px solid blue;
margin: 3px 2px;
}
#computerOrders
{
width:50%;
height:100%;
background-color:white;
}
#orderInfo
{
width:50%;
height:100%;
background-color:white;
}
I want to replace the after-submission checks in the form with on-the-fly completeness and correctness checks that are performed when a form field loses focus.
How can I do this?
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE HTML>
<html>
<head>
<title>Form</title>
<style>
body {
width: 500px;
}
.part {
width: 100%;
padding: 5px;
border-bottom: 1px solid #000;
}
label {
margin-right: 5px;
}
.label-left {
text-align: right;
}
.label-right {
text-align: left;
}
.error {
color: #cc0000;
}
</style>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
//$(document).ready(function() {
function myValidateEMailAddress(email_address) {
var email_pattern = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
return email_pattern.test(email_address);
}
function checkPassword(pwd_str) {
var my_pwd_pattern = /^(?=.*[a-zA-Z].*[a-zA-Z])(?=.*\d.*\d)[a-zA-Z0-9_]{6,20}$/;
return my_pwd_pattern.test(pwd_str);
}
function validatePhoneNumber(phone_number) {
var phone_pattern = /^(\(?\+?[0-9]*\)?)?[0-9_\- \(\)]*$/;
return phone_pattern.test(phone_number);
}
$(document).ready(function() {
$('#form').submit(function(e) {
var my_errors = false;
$('.part> .error').remove();
$('#my_submission').empty();
$(':text, :password, textarea').each(function() {
$(this).val($.trim($(this).val()));
if ($(this).val() == '') {
$(this).parent().append('<div class="error">Please provide a value</div>');
my_errors = true;
}
});
if ($('#email').val() != '') {
if (!myValidateEMailAddress($('#email').val())) {
$('#email').parent().append('<div class="error">Please provide a correct e-mail address</div>');
my_errors = true;
}
}
if ($('#your_password').val() != '') {
if (!checkPassword($('#your_password').val())) {
$('#your_password').parent().append('<div class="error">Please provide a correct password.</div>');
my_errors = true;
}
}
if ($('#phone').val() != '') {
if (!validatePhoneNumber($('#phone').val())) {
$('#phone').parent().append('<div class="error">Please provide a correct phone number.</div>');
my_errors = true;
}
}
if ($('#addresses option:selected').val() == '') {
$('#addresses').parent().append('<div class="error">Please select one item</div>');
my_errors = true;
}
if ($(':radio[name="sex"]:checked').length == 0) {
$(':radio[name="sex"]:first').parent().after('<div class="error">Please select one item</div>');
my_errors = true;
}
if ($(':radio[name="subscription"]:checked').length == 0) {
$(':radio[name="subscription"]:first').parent().after('<div class="error">Please select one item</div>');
my_errors = true;
}
if ($('#likes option:selected').val() == '') {
$('#likes').parent().append('<div class="error">Please select one item</div>');
my_errors = true;
}
if (my_errors) {
return false;
}
else {
e.preventDefault();
var my_submission_array = $('#form').serialize().split('&');
if (my_submission_array.length > 0) {
$('#my_submission').html('<h2>Submitted Elements</h2><ul></ul>');
for (var i = 0; i < my_submission_array.length; i++) {
var my_pair = my_submission_array[i].split('=');
$('#my_submission > ul').append('<li>' + my_pair[0] + ': ' + my_pair[1] + '</li>\n');
}
}
}
});
});
// });
</script>
</head>
<body>
<h3>Output:</h3>
<h2>My Questionnaire</h2>
<form name="form" id="form" action="" method="post">
<div class="part">
<label for="addresses" class="label-left">How should you be addressed?</label>
<select name="addresses" id="addresses">
<option value="">Please select one</option>
<option value="first">Mr.</option>
<option value="second">Madam</option>
<option value="third">Miss</option>
<option value="fourth">Dr.</option>
<option value="fifth">Pr.</option>
</select>
</div>
<div class="part">
<fieldset>
<legend>Sex:</legend>
<input type="radio" name="sex" id="group1" value="1">
<label for="group1" class="label-right">Male</label>
<input type="radio" name="sex" id="group2" value="2">
<label for="group2" class="label-right">Female</label>
</fieldset>
</div>
<div class="part">
<label for="last_name" class="label-left">Last Name: </label>
<input type="text" name="last_name" id="last_name">
</div>
<div class="part">
<label for="first_name" class="label-left">First Name: </label>
<input type="text" name="first_name" id="first_name">
</div>
<div class="part">
<label for="email" class="label-left">E-Mail: </label>
<input type="text" name="email" id="email">
</div>
<div class="part">
<label for="your_password">Password:</label>
<input type="password" name="your_password" id="your_password" size="10" maxlength="20">
</div>
<div class="part">
<label for="phone" class="label-left">Phone number: </label>
<input type="text" name="phone" id="phone">
</div>
<div class="part">
<label for="likes" class="label-left">What are your likes?</label>
<select name="likes" id="likes">
<option value="">Please select one</option>
<option value="first">Programming</option>
<option value="second"> African literature</option>
<option value="third">Poetry</option>
<option value="four">Dancing</option>
</select>
</div>
<div class="part">
<fieldset>
<legend>Do you want to receive our newsletter ?</legend>
<input type="radio" name="subscription" id="group1" value="1">
<label for="group1" class="label-right">Yes</label>
<input type="radio" name="letter" id="group2" value="2">
<label for="group2" class="label-right">No</label>
</fieldset>
</div>
<div class="part">
<label for="comments" class="label-left">Write some comments below:</label>
<textarea name="comments" id="comments" cols="40" rows="3"></textarea>
</div>
<div class="part">
<input type="submit" name="submit" id="submit" value="Submit Form">
</div>
<div id="my_submission"></div>
</form>
</body>
</html>
Before I continue answering, I should note that you're putting jQuery script before <html> tag. This is incorrect. It has to be in <head>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
...
performed when a form field loses focus
An element loses focus when you click away from it. jQuery happends to have a blur event for this occasion:
$('input').on('blur', function() {
// your code here
});
So you might want to do it this way:
$('#email').on('blur', function() {
var emailVal = $(this).val();
if (!emailVal || !myValidateEMailAddress(emailVal)) {
$(this).parent().append('<div class="error">Please provide a correct e-mail address</div>');
my_errors = true;
}
});
the rest of the code might look similar.