Check out form to calculate total cost of items - javascript

So I am making an ecommerce style website where people can purchase smartphones. In this website I have a checkout form where users can select what phone they wish to choose and then depending on the quantity the form displays the total cost for the user. However since I am using drop down options I am not sure on how to go about getting the value of the phone, multiplying it by the quantity and displaying the total cost at the bottom.
div class="contact-wrap">
<div class="title-box">
<b>Check Out</b>
</div>
<div id="form1">
<img id="phone" src="iphone6.jpg" width="294" height="320"/>
<select id="phoneList">
<option value="iphone1.jpg">Apple iPhone 11 Pro Max (2019) 512GB Silver</option>
<option value="iphone2.jpg">Apple iPhone 11 (2019) 128GB Black</option>
<option value="iphone3.jpg">Apple iPhone 11 (2019) 256GB White</option>
</select>
<select id="quantity">
<p>Quantity</p>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
</div>
<div id="form2">
<form name="myForm" action="/action_page.php" onsubmit="return validateForm()" method="post">
<p>First name: </p><input type="text" name="fname">
<p>Last name: </p><input type="text" name="lname">
<p>Email address: </p><textarea id="email" rows = "1" cols = "40" name="email"></textarea>
<p>Shipping address </p><textarea id="shipping" rows = "6" cols = "40" name="shipping"></textarea><br>
<input style="float:bottom; margin-top:20px" type="submit" value="Order">
</form>
</div>
</div>
<script>
function setPhone() {
var img = document.getElementById("phone");
img.src = this.value;
return false;
}
document.getElementById("phoneList").onchange = setPhone;
function validateForm() {
var x = document.forms["myForm"]["fname"].value;
var y = document.forms["myForm"]["lname"].value;
var email = document.forms["myForm"]["email"].value;
var shipping = document.forms["myForm"]["shipping"].value;
if (x == "") {
alert("First name must be filled out");
return false;
}
else if (y == "") {
alert("Last name must be filled out");
return false;
}
else if (parseInt("0"+x, 10) > 0 || parseInt("0"+y, 10) > 0){
alert("Numbers not permissable for name");
return false;
}
else if (email == "") {
alert("Email must be filled out");
return false;
}
else if (shipping == "") {
alert("Shipping address must be filled out");
return false;
}
}
</script>

Doing some slight edits of your select to include attributes so it looks as follows:
<select id="phoneList">
<option value="iphone1.jpg" data-cost="100">Apple iPhone 11 Pro Max (2019) 512GB Silver</option>
<option value="iphone2.jpg" data-cost="200">Apple iPhone 11 (2019) 128GB Black</option>
<option value="iphone3.jpg" data-cost="300">Apple iPhone 11 (2019) 256GB White</option>
</select>
Then by getting the selected index and the data-cost defined above using
var i = phoneList.selectedIndex;
var phoneCost = document.getElementById("phoneList").getElementsByTagName("option")[i].getAttribute("data-cost");
you can get the cost of the selected phone.
Then just multiply the cost of the phone by the quantity from
document.getElementById("quantity").value;
and display it somewhere on your page.
So when the user selects an option in the dropdown call a function along the lines of
<script>
function CalcCosts() {
//Get user selected items
var i = phoneList.selectedIndex;
var phonecost = document.getElementById("phoneList").getElementsByTagName("option")[i].getAttribute("data-cost");
var quantity = parseInt(document.getElementById("quantity").value);
//Display on page
document.getElementById("PLACETODISPLAY").innerHTML = phonecost * quantity;
}
</script>
You could call the function using the onclick of the dropdowns as follows
<select id="quantity" onclick="CalcCosts()">
<p>Quantity</p>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
Edit:
Include suggestions from comments.

Related

How do I use the compute() event properly for a calculator

I'm trying to code a sample rate calculator and I need the compute() function to display text with certain parameters each time it's pressed, but it's not working
I'll paste the code samples below.
var principal = document.getElementById("principal").value;
var rate = document.getElementById("rate").value;
var years = document.getElementById("years").value;
var interest = principal * years * rate /100;
var year = new Date().getFullYear()+parseInt(years);
function compute()
{
var result = document.getElementById("result").value;
document.getElementById("result").innerHTML = "If you deposit "+principal+",\<br\>at an interest rate of "+rate+"%\<br\>You will receive an amount of "+amount+",\<br\>in the year "+year+"\<br\>";
}
function checkdata() {
//create references to the input elements we wish to validate
var years = document.getElementById("years");
var principal = document.getElementById("Principal");
//Check if "No of Years" field is actual year
if (years.value != "year") {
alert("Please input the actual year");
years.focus();
return false;
}
//Check if principal field is zero or negative
if (principal.value == "0" || principal.value == "negativ no") {
alert("Enter a positive number");
principal.focus();
return false;
}
//If all is well return true.
alert("Form validation is successful.")
return true;
}
function updateValue(event) {
document.getElementById("rate_val").innerText = event.value;
}
<!DOCTYPE html>
<html>
<head>
<script src="script.js"></script>
<link rel="stylesheet" href="style.css">
<title>Simple Interest Calculator</title>
</head>
<body>
<div class="container">
<h1>Simple Interest Calculator</h1>
<form id="form1">
<label for="Amount"></label>
Amount <input type="number" id="principal">
<br/>
<br/>
<label for="Interest Rate"></label>
<label for="Interest Rate">Interest Rate</label>
<input onchange=updateValue(this) type="range" id="rate" min="1" max="20" step="0.25" default value="10.25">
<span id="rate_val">10.25%</span>
<br/>
<br/>
<label for="No. of Years"></label>
No. of Years <select id="years">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
<!-- fill in the rest of the values-->
</select>
<br/>
<br/>
<label for="Compute Interest"></label>
<button onclick="compute()">Compute Interest</button>
<br/>
<br/>
<span id="result"></span>
<br/>
<br/>
</form>
<br/>
<br/>
<footer>© Everyone Can get Rich.<br/>This Calculator belongs to Igho Emorhokpor</footer>
</div>
</body>
</html>
The main issue in your code is because you've attached the onclick attribute to the button which submits the form. As the form submission is not being prevented, the page is redirected before you can update the DOM.
To fix this, hook the event handler to the submit event of the form and call preventDefault() on the event which is passed to the handler as an argument.
In addition, there's some other issues in your code.
You should avoid using onX attributes as they are no longer good practice. Attach your event handlers using unobtrusive JS, such as addEventListener().
amount is not defined anywhere. You will need to declare and set this variable. I've used a dummy value for it in the code below.
You need to retrieve the value properties of your form controls when the button is clicked, not when the page loads. This is to ensure that the values the user enters are retrieved from the DOM.
Wrap the field controls and the label text within the label element. Leaving them empty serves no purpose.
Avoid using the <br /> tag as much as possible. Given the above change to your label elements, apply CSS to add the margin underneath them instead.
In the checkData() function, years is a selection of integer values, so comparing those values to a "year" string is redundant.
In addition, to detect a negative number compare it to < 0, not the string "negative no"
With all that said, try this:
let principalEl = document.querySelector("#principal");
let rateEl = document.querySelector("#rate");
let rateOutputEl = document.querySelector('#rate_val');
let yearsEl = document.querySelector("#years");
let formEl = document.querySelector('#form1');
let result = document.querySelector('#result');
let amount = '???';
formEl.addEventListener('submit', e => {
e.preventDefault();
if (!checkData())
return;
let principal = principalEl.value;
let rate = rateEl.value;
let year = yearsEl.value;
let interest = principal.value * years.value * rate.value / 100;
let endYear = new Date().getFullYear() + parseInt(years.value);
result.innerHTML = `If you deposit ${principal},<br \>at an interest rate of ${rate}%<br \>You will receive an amount of ${amount},<br \>in the year ${endYear}<br \>`;
});
rateEl.addEventListener('input', e => {
rateOutputEl.textContent = e.target.value + '%';
});
function checkData() {
let principal = principalEl.value;
if (!principal || parseFloat(principal) < 0) {
alert("Enter a positive number");
principalEl.focus();
return false;
}
return true;
}
label {
display: block;
margin-bottom: 20px;
}
form {
margin-bottom: 50px;
}
<div class="container">
<h1>Simple Interest Calculator</h1>
<form id="form1">
<label for="Amount">
Amount
<input type="number" id="principal">
</label>
<label for="Interest Rate">Interest Rate
<input type="range" id="rate" min="1" max="20" step="0.25" value="10.25" />
<span id="rate_val">10.25%</span>
</label>
<label for="No. of Years">
No. of Years
<select id="years">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
<!-- fill in the rest of the values-->
</select>
</label>
<label for="Compute Interest">
<button type="submit">Compute Interest</button>
</label>
<span id="result"></span>
</form>
<footer>© Everyone Can get Rich.<br/>This Calculator belongs to Igho Emorhokpor</footer>
</div>
function compute()
{
var result = document.getElementById("result").value;
document.getElementById("result").innerHTML = ~If you deposit ${principal} at an ${interest} rate of ${rate}% You will receive an amount of ${amount} in the year ${year}~;
}

Require the textarea to be filled in when certain option is selected

I need the textarea to be filled when "Other" is selected.
This is what I have, I thought it will work. But nothing shows up when other is selected and textarea is left blank.
html:
<form onsubmit="return validation()">
<span>Reason for inquiry: <span>
<select style="color:black" name="reasons">
<option value="catering">Catering</option>
<option value="private party">Private Party</option>
<option value="feedback">Feedback</option>
<option id="selectedOther" value="other">Other</option>
</select>
</form>
JS:
function validation(){
otherInquiry()
}
function otherInquiry(){
var x = document.getElementById("selectedOther").value;
if (document.getElementsByTagName("select") == x){
if(document.getElementById("txtArea").value == ""){
alert("Please tell us your reason of inquiry")
}
return false;
}
}

JavaScript Form Validation not working entirely

I am trying to have JavaScript code validate all the elements of this form but for some reason the select box doesn't validated. The user can fill in all the blanks except for the select box and the JavaScript does not catch it. Any ideas as to what I am missing? Thanks.
<script type="text/javascript">
function validateForm() {
var ageErr = document.getElementById('ageErr');
var nameErr = document.getElementById('nameErr');
var radioErr = document.getElementById('radioErr');
var results = document.getElementById('results');
var theName = document.formContact.theName;
var theAge = document.formContact.theAge;
var theRadioGp = document.formContact.contact;
var theSelect = document.formContact.theSelect;
var chkValue;
if(theName.value =="") {
nameErr.innerHTML = "A name is required ";
theName.focus();
return false;
}else {
nameErr.innerHTML= "";
}
if(theAge.value ==""){
ageErr.innerHTML = "An age is required";
theAge.focus();
return false;
}else {
nameErr.innerHTML = "";
}
if(theAge.vale =="") {
age.Err.innerHTML = "An age is required";
theAge.focus();
return false;
} else if (isNaN(theAge.value)) {
ageErr.innerHTML = "Age should be a number";
theAge.select();
} else if (theAge.value < 3 || theAge.value > 120) {
ageErr.innerHTML = "Please enter your real Age";
theAge.select();
return false;
} else{
ageErr.innerHTML = "";
}
for(var i=0; i < theRadioGp.length; i++) {
if(theRadioGp[i].checked ==true) {
chkValue = theRadioGp[i].value;
}
}
if(chkValue == undefined) {
alert('You need to slect a method of contact');
return false;
}
if(theSelect.options[theSelect.selectedIndex].text == "<--PLEASE SELECT ONE-->")
{alert("You need to select an option");
return false;
}else {
alert("Your have selected "+theSelect.options[theSelect.selectedIndex].text);
}
alert("Your form has been completed. Great Job!!");
}
</script>
</head>
<body>
<form action="" id="formContact" method="post" onsubmit="return validateForm();" name="formContact">
<p>Name:<br />
<input type="text" name="theName"><span class="err" id="nameErr"></span>
</p>
<p>Age:<br />
<input type="text" name="theAge"><span class="err" id="ageErr"></span>
</p>
<p>
<p>How may we contact you?<br>
<input type="radio" name="contact" value="email">Email<br>
<input type="radio" name="contact" value="no contact">No Contact<br>
</p>
<p>Please coose a selection below:<br>
<select name="theSelect">
<option><--PLEASE SELECT ONE -->
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
</p>
<p><input type="submit" value="Submit" name="btnSubmit" ">
</form>
<span id="results"></span>
</body>
</html>
Your HTML isn't valid. Replace your select part with following
<select name="theSelect">
<option><--PLEASE SELECT ONE--></option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
Or use a numeric value for the default option
<select name="theSelect">
<option value="0">PLEASE SELECT AN OPTION</option>
<option value="1">One</option>
...
</select>
And check the value (not the text selected)
if(theSelect.options[theSelect.selectedIndex].value == 0){
alert("You need to select an option");
return false;
}else {
alert("Your have selected " + theSelect.options[theSelect.selectedIndex].text);
}
Why not use selectedIndex without the text?
Example:
<select id="mytest">
<option value="-1"><--PLEASE SELECT ONE--></option>
<option value="1">Test One</option>
<option value="2">Test Two</option>
</select>
Then
if(theSelect.selectedIndex == -1)
{alert("You need to select an option");
return false;
}else {
the rest

Form not validating before Submit (JavaScript)

I have a form written in JavaScript that works correctly when I submit. However, there is one conditional which I would like to be validated before the user hits the submit button. If the user chooses "None" on the dropdown menu, I want the other dropdown menu and textbox to be disabled before the user tries to submit. This is what I've done so far, but nothing seems to happen everytime I choose "None":
<form name="my_form" onsubmit="return submit()" action="/test" method="post">
<select id="month">
<option value="None">None</option>
<option value="0">January</option>
<option value="1">February</option>
<option value="2">March</option>
<option value="3">April</option>
<option value="4">May</option>
<option value="5">June</option>
<option value="6">July</option>
<option value="7">August</option>
<option value="8">September</option>
<option value="9">October</option>
<option value="10">November</option>
<option value="11">December</option>
</select>
<select id="day">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
</select>
<input type="text" name="year" placeholder="Year" />
<input type="submit" value="Submit" />
</form>
<script>
function submit(){
var get_month_value = month.options[month.selectedIndex].text;
if(get_month_value == "None"){
document.getElementById("year").disabled = true;
document.getElementById("day").disabled = true;
return false;
}
else if(year == ""){
alert("Year must be filled out");
return false;
}
</script>
Where am I going wrong with this? Any help would be appreciated. Thanks.
Give form an ID and remove the onsubmit function:
<form id="my_form" name="my_form" action="/test" method="post">
Place the submit button outside the form and add the onclick function:
<input type="submit" value="Submit" onclick="submit();" />
Give year text field an ID:
<input type="text" id="year" name="year" placeholder="Year" />
Javascript:
function submit() {
var select = document.getElementById("month");
var get_month_value = select.options[select.selectedIndex].value;
var year = document.getElementById('year').value;
if ((get_month_value == "None") || (year == "")) {
alert("Please fill out the required fields");
} else {
document.getElementById("my_form").submit();
}
}
DEMO
HTML5 Date picker with "required" attribute(works):
<form id="dateForm" name="dateForm" action="/test" method="post">
Date: <input type="date" name="date" required />
<input type="submit" />
</form>
No need for JScript and html for dropdowns.
DEMO
Your code has the following errors:-
First of all you can't give your function the name submit in your form attribute.
You are missing } at the end of your function.
Your Input Text should have id=year not name.
Month is not defined.
year is not defined.
Change
these lines in your HTML:-
<form name="my_form" onsubmit="return validateForm()" action="/test" method="post">
<input type="text" id="year" placeholder="Year" />
Javascript:-
function validateForm(){
var month = document.getElementById('month');
var year = document.getElementById('year').value;
var get_month_value = month.options[month.selectedIndex].text;
if(get_month_value == "None"){
document.getElementById("year").disabled = true;
document.getElementById("day").disabled = true;
return false;
}
else if(year == ""){
alert("Year must be filled out");
return false;
}
}

validate forms with js

Hi I had my script working then I ran it through w3 validator and changed what I told me was wrong and now it stops validating at the first postcode, I have stuffed up and cant remember what was changed bigg lesson learnt do 1 thing at a time, I have been pulling my hair out trying to get it working again but cant figure out how if any 1 can take to time to look at it, I would greatly appreciate it, thanks
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<title>Joes Fruit and Vegetable Store</title>
<script>
//calender dropdown menu
var monthtext = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sept', 'Oct', 'Nov', 'Dec'];
function populatedropdown(dayfield, monthfield, yearfield) {
var today = new Date()
var dayfield = document.getElementById(dayfield)
var monthfield = document.getElementById(monthfield)
var yearfield = document.getElementById(yearfield)
for (var i = 0; i < 31; i++)
dayfield.options[i] = new Option(i, i + 1)
dayfield.options[today.getDate()] = new Option(today.getDate(), today.getDate(), true, true) //select today's day
for (var m = 0; m < 12; m++)
monthfield.options[m] = new Option(monthtext[m], monthtext[m])
monthfield.options[today.getMonth()] = new Option(monthtext[today.getMonth()], monthtext[today.getMonth()], true, true) //select today's month
var thisyear = today.getFullYear()
for (var y = 0; y < 20; y++) {
yearfield.options[y] = new Option(thisyear, thisyear)
thisyear += 1
}
yearfield.options[0] = new Option(today.getFullYear(), today.getFullYear(), true, true) //select today's year
}
// function validate
function validate_form() {
valid = true;
// validate name
/* if ( document.input.name.value == "" )
{
alert ( "Please enter your name" );
valid = false;
}
// validate address
if ( document.input.address.value == "" )
{
alert ( "Please enter your address address" );
valid = false;
}
// validate suburb town
if ( document.input.town.value == "" )
{
alert ( "Please enter your Suburb or town" );
valid = false;
}
// validate postcode
var y = document.getElementById("postcode").value;
if(isNaN(y)||y.indexOf(" ")!=-1)
{
alert("Postcode must be in numbers.");
document.getElementById("postcode").focus();
return false;
}
if (y.length>4 || y.length<4)
{
alert("Postcode should be 4 digit");
document.getElementById("postcode").focus();
return false;
}
*/
// validate home phone
var y = document.getElementById('hphone').value;
if (isNaN(y) || y.indexOf(" ") != -1) {
alert("Home Phone number must be in numbers.");
document.getElementById('hphone').focus();
return false;
}
if (y.length > 10 || y.length < 10) {
alert("Home Phone number should be 10 digit");
document.getElementById('hphone').focus();
return false;
}
// validate work phone
var y = document.getElementById('wphone').value;
if (isNaN(y) || y.indexOf(" ") != -1) {
alert("work Phone number must be in numbers.");
document.getElementById('wphone').focus();
return false;
}
if (y.length > 10 || y.length < 10) {
alert("Work Phone number should be 10 digit");
document.getElementById('wphone').focus();
return false;
}
// validate fax
var y = document.getElementById('fax').value;
if (isNaN(y) || y.indexOf(" ") != -1) {
alert("Fax number must be in numbers.");
document.getElementById('fax').focus();
return false;
}
if (y.length > 10 || y.length < 10) {
alert("Fax Phone number should be 10 digit");
document.getElementById('fax').focus();
return false;
}
// validate email
{
var x = document.forms["input"]["email"].value;
var atpos = x.indexOf("#");
var dotpos = x.lastIndexOf(".");
if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= x.length) {
alert("Not a valid e-mail address");
return false;
}
}
// validate radio buttons
var o = document.getElementById('rad1');
var t = document.getElementById('rad2');
if ((o.checked == false) && (t.checked == true)) {
// validate alternative address
if (document.input.street.value == "") {
alert("Please enter alternative address address");
valid = false;
}
// validate suburb town
if (document.input.suburb.value == "") {
alert("Please enter alternative Suburb or town");
valid = false;
}
} // validate postcode
var y = document.getElementById('postcode2').value;
if (isNaN(y) || y.indexOf(" ") != -1) {
alert("Postcode must be in numbers.");
document.getElementById('postcode2').focus();
return false;
}
if (y.length > 4 || y.length < 4) {
alert("Alternative Postcode should be 4 digit");
document.getElementById('postcode2').focus();
return false;
}
// validate message box
var o = document.getElementById('card');
if ((o.checked == true)) {
if (document.input.message.value == "") {
alert("Please enter message");
valid = false;
}
return valid;
}
}
</script>
</head>
<body> <b>Order form for Joe's Fruit Shop</B><br><br>
<b> * means you must fill in the details.</B><br><br>
<b>Your details:</b>
<br>
<br>
<!-- Beggining of Form -->
<form name="input" action="cal2.html" onsubmit="validate_form ()">
<!--name form -->* Name:
<input type="text" name="name" onclick="this.value='';" value="Enter your name with first">
<br>
<br>
<!-- Address form -->* Address:
<input type="text" name="address" onclick="this.value='';" value="Enter your street address">
<br>
<br>
<!-- Suburb state dropdown form-->* Suburb or Town:
<input type="text" name="town" onclick="this.value='';"
value="suburb">State:
<select name="state">
<option value="NSW">NSW</option>
<option selected="selected" value="QLD">QLD</option>
<option value="SA">SA</option>
<option value="WA">WA</option>
<option value="TAS">TAS</option>
<option value="VIC">VIC</option>
<option value="NT">NT</option>
<option value="ACT">ACT</option>
</select>
<!-- post code form -->* Postcode:
<input type=text name="postcode" onclick="this.value='';" value="****">
<br>
<br>
<!-- Home phone form-->* Phone:
<input type=text name="hphone" onclick="this.value='';" value="x-xxxx-xxx">
<!-- work phone form -->Work phone
<input type=text name="wphone" onclick="this.value='';" value="x-xxxx-xxx">
<br>
<br>
<!-- Fax form-->*Fax:
<input type=text name="fax" onclick="this.value='';" value="0x-xxxx-xxx">
<!-- Email form-->Email address:
<input type=text name="email" onclick="this.value='';" onsubmit="return validateForm();"
value="Enter your current email">
<br>
<br>
<br>
<!-- credit card--> <b>Credit card details:</b>
<br>
<br>* Type:
<select name="credit card">
<option selected="selected" value="AMEX">Amex</option>
<option value="Visa">Visa</option>
<option value="Mastercard">Mastercard</option>
</select>*Expiry date:
<select name="expiration_month">
<option value="">Choose...</option>
<option selected="selected" value="1">January</option>
<option value="2">Febuary</option>
<option value="3">March</option>
<option value="4">April</option>
<option value="5">May</option>
<option value="6">June</option>
<option value="7">July</option>
<option value="8">August</option>
<option value="9">September</option>
<option value="10">October</option>
<option value="11">November</option>
<option value="12">December</option>
</select>
<select name="expiration_year">
<option value="">Choose...</option>
<option selected="selected" value="2012">2012</option>
<option value="2013">2013</option>
<option value="2014">2014</option>
<option value="2015">2015</option>
<option value="2016">2016</option>
<option value="2017">2017</option>
<option value="2018">2018</option>
<option value="2019">2019</option>
<option value="2020">2020</option>
</select>
<br>
<br>
<B>Purchase details</B><br><br> <!-- Product dropdown form-->
* Product:
<select name="product">
<option value="carrot">Bag of carrots</option>
<option value="zucchini">Zucchini</option>
<option value="cabbage">Cabbage</option>
<option value="grapes">Grapes</option>
<option value="tomatoes">TAS</option>
<option value="apples">Apples</option>
<option value="banana">banana</option>
<option selected="selected" value="cucumber">Cucumber</option>
</select>
<!-- Quantity dropdown form-->
Quantity:
<select name="quantity">
<option selected="selected" value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
</select>
<br><br><br>
* <B>Deliver to:</B>
<br><br>
<!-- Address Radio buttons-->
<input type='radio' id="rad1" name='radio' value='Home address' checked="checked">Home Address<br>
<input type='radio' id="rad2" name='radio' value='Other address'/>Other Address<br><br>
<!--other address-->
<!-- street form-->
Street <input type=text name="street" onclick="this.value='';" value="Street"><br><br>
<!-- Suburb form-->
Suburb <input type=text name="suburb" onclick="this.value='';" value="Suburb or town"><br><br>
<!-- State dropdown form-->
State <select name="state">
<option value="NSW">NSW</option>
<option selected="selected" value="QLD">QLD</option>
<option value="SA">SA</option>
<option value="WA">WA</option>
<option value="TAS">TAS</option>
<option value="VIC">VIC</option>
<option value="NT">NT</option>
<option value="ACT">ACT</option>
</select><br><br>
<!-- post code form -->
Postcode:<input type=text name="postcode2" onclick="this.value='';" value="****"><br><br><br>
* Date delivery required:
<!-- Calender drop down menu-->
<select id="daydropdown">
</select>
<select id="monthdropdown">
</select>
<select id="yeardropdown">
</select>
<script type="text/javascript">
//populatedropdown(id_of_day_select, id_of_month_select, id_of_year_select)
window.onload=function(){
populatedropdown("daydropdown", "monthdropdown", "yeardropdown")
}
</script>
<br><br>
<!-- include a card option-->
Include a card: <input type="checkbox" name="card" value="Yes">Yes<br><br>
Personal message on card: <textarea rows="10" name="message" cols="30" onclick="this.value='';" >Enter your personal message here</textarea><br><br>
Click on <b>Submit</b> when done; click on <b> Clear form</b> to reset.
<!-- submit button-->
<input type="submit" value="Submit">
<!-- reset button-->
<input type="reset" value="Reset">
</form>
</body>
</html>
Your scripts are failing as you are trying to get elements by Id and checking the value property of a null.
var y = document.getElementById('hphone').value;
This throws an exception and exits, the form then submits
Give your elements Ids to match the name attribute and it should be okay
<input type=text name="hphone" id="hphone" onclick="this.value='';" value="x-xxxx-xxx">
change your onsubmit attribute to the follow to cancel the submit on validation error
<form name="input" action="cal2.html" onsubmit="return validate_form ()">
To check against a default value, you could added a data attribute and cross check the value in the validation.
* Phone: <input type=text name="hphone" id="hphone" onclick="this.value='';" data-default="x-xxxx-xxx" value="x-xxxx-xxx">
var element = document.getElementById('hphone');
var y = element.value;
var defValue = element.attributes["data-default"].value;
if(isNaN(y)||y.indexOf(" ")!=-1|| y === defValue )
{
alert("Home Phone number must be in numbers.");
document.getElementById('hphone').focus();
return false;
}
If you are targetting HTML5 compliant browsers you could use the placeholder attribute.
http://www.w3schools.com/html5/att_input_placeholder.asp

Categories

Resources