I want to add +10% to a value if that value is selected , but before i can implement it i need to make it work properly , first of the page shouldn't refresh and when i add a value and then i want to change it to another i want the old value from the other textbox to subtract ... i tried with a simple if/else if / else statement but because of the first error it won't work and i even ain't sure that it is working right. Here is the code:
<!doctype html>
<html>
<head>
<title>lol</title>
<meta charset="utf-8">
</head>
<body>
<form action="">
<input type="text" id="hp">
<input type="text" id="ea">
<input type="text" id="ed">
<input type="text" id="pa">
<input type="text" id="pd">
<input type="text" id="sp">
<select>
<option value="hp">HP</option>
<option value="ea">EA</option>
<option value="ed">ED</option>
<option value="pa">PA</option>
<option value="pd">PD</option>
<option value="sp">SP</option>
</select>
<input type="submit" id="sub" onClick = "return at()">
</form>
<script type="text/javascript">
function at () {
var a = document.form.select.options,
i = document.form.select.selectedIndex,
ea = Number(document.form.ea.value),
ed = Number(document.form.ed.value),
hp = Number(document.form.hp.value),
pd = Number(document.form.pd.value),
pa = Number(document.form.pa.value),
sp = Number(document.form.sp.value),
eaS,edS,pdS,paS,spS,hpS = 0;
if(a[i].text === "hp"){
hpS = hp*0.1;
}else if(a[i].text === "ea"){
eaS = ea*0.1
}else if(a[i].text === "ed"){
edS = ed*0.1
}else if(a[i].text === "pa"){
paS = pa*0.1
}else if(a[i].text === "pd"){
pdS = pd*0.1
}else if(a[i].text === "sa"){
spS = sp*0.1
}
document.form.ea.value = eaS;
document.form.ed.value = edS;
document.form.hp.value = hpS;
document.form.pd.value = pdS;
document.form.pa.value = paS;
document.form.sp.value = spS;
return false;
}
</script>
</body>
</html>
Look at the JavaScript console
I am willing to bet it has the error that says something like. If you do not see the error, set up your console so it persists errors across page navigation.
Uncaught TypeError: Cannot read property 'select' of undefined
You are looking for an element with the name of form and one with the name of select, but your form/select has no name.
<form action="">
<select>
should be
<form name="form" action="">
<select name="select">
Ideally you would drop the document.name.name syntax and use getElementById. Put an id on the select and form and reference the inputs that way too. Also a switch statement would be your friend.
Your code could be written without if statements, just use look ups based on the selects value.
function at() {
var sel = document.getElementById("mySelect");
var val = sel.options[sel.options.selectedIndex].value;
var input = document.getElementById(val);
if (input) {
var val = input.value;
resetValues();
input.value = parseFloat(val) * .1;
}
}
function resetValues() {
var inputs = document.getElementById("myForm").getElementsByTagName("input");
for (var i=0;i<inputs.length;i++) {
var inp = inputs[i];
if (inp.type==="text") inp.value = 0;
}
}
JSFiddle - Running example
many changes needed :
<!doctype html>
<html>
<head>
<title>lol</title>
<meta charset="utf-8">
</head>
<body>
<form action="">
<input type="text" name="hp" id="hp">
<input type="text" name="ea" id="ea">
<input type="text" name="ed" id="ed">
<input type="text" name="pa" id="pa">
<input type="text" name="pd" id="pd">
<input type="text" name="sp" id="sp">
<select id="mySelect">
<option value="hp">HP</option>
<option value="ea">EA</option>
<option value="ed">ED</option>
<option value="pa">PA</option>
<option value="pd">PD</option>
<option value="sp">SP</option>
</select>
<input type="button" id="sub" value="Submit" onClick = "return at()">
</form>
<script type="text/javascript">
function at () {
var a = document.getElementById('mySelect').options,
i = document.getElementById('mySelect').selectedIndex,
ea = Number(document.forms[0].ea.value),
ed = Number(document.forms[0].ed.value),
hp = Number(document.forms[0].hp.value),
pd = Number(document.forms[0].pd.value),
pa = Number(document.forms[0].pa.value),
sp = Number(document.forms[0].sp.value),
eaS,edS,pdS,paS,spS,hpS = 0;
if(a[i].text === "HP"){
hpS = hp*0.1;
}
if(a[i].text === "EA"){
eaS = ea*0.1
}
if(a[i].text === "ED"){
edS = ed*0.1
}
if(a[i].text === "PA"){
paS = pa*0.1
}
if(a[i].text === "PD"){
pdS = pd*0.1
}
if(a[i].text === "SA"){
spS = sp*0.1
}
document.forms[0].ea.value = eaS;
document.forms[0].ed.value = edS;
document.forms[0].hp.value = hpS;
document.forms[0].pd.value = pdS;
document.forms[0].pa.value = paS;
document.forms[0].sp.value = spS;
return false;
}
</script>
</body>
</html>
Something like this
<form action="">
<input type="text" id="hp">
<input type="text" id="ea">
<input type="text" id="ed">
<input type="text" id="pa">
<input type="text" id="pd">
<input type="text" id="sp">
<select name="select">
<option value="hp">HP</option>
<option value="ea">EA</option>
<option value="ed">ED</option>
<option value="pa">PA</option>
<option value="pd">PD</option>
<option value="sp">SP</option>
</select>
<input type="button" id="sub" value="Submit">
</form>
var sub = document.getElementById("sub");
function at() {
var a = document.forms[0].select.options,
i = document.forms[0].select.selectedIndex,
ea = Number(document.forms[0].ea.value),
ed = Number(document.forms[0].ed.value),
hp = Number(document.forms[0].hp.value),
pd = Number(document.forms[0].pd.value),
pa = Number(document.forms[0].pa.value),
sp = Number(document.forms[0].sp.value),
eaS, edS, pdS, paS, spS, hpS;
eaS = edS = pdS = paS = spS = hpS = 0;
if (a[i].text === "HP") {
hpS = hp * 0.1;
} else if (a[i].text === "EA") {
eaS = ea * 0.1
} else if (a[i].text === "ED") {
edS = ed * 0.1
} else if (a[i].text === "PA") {
paS = pa * 0.1
} else if (a[i].text === "PD") {
pdS = pd * 0.1
} else if (a[i].text === "SA") {
spS = sp * 0.1
}
document.forms[0].ea.value = eaS;
document.forms[0].ed.value = edS;
document.forms[0].hp.value = hpS;
document.forms[0].pd.value = pdS;
document.forms[0].pa.value = paS;
document.forms[0].sp.value = spS;
return false;
}
sub.addEventListener("click", at, false);
ob jsfiddle
I have not fixed every problem that you may have with your code, just the main part.And you can use this fiddle to work through your other problems.
Related
console img
const num1Element = document.querySelector("#num1");
const num2Element = document.querySelector("#num2");
const resultElement = document.querySelector("#result");
const operatorlememt = document.querySelectorAll("[data-operation]")
function summary() {
if (operatorElememt == "+") {
const sumElement = Number(num1.value) + Number(num2.value);
resultElement.innerHTML = sumElement;
}
}
function multi() {
if (operatorElememt == "*") {
const multiElement = Number(num1.value) * Number(num2.value);
resultElement.innerHTML = multiElement;
}
}
function divide() {
if (operatorElememt == "/") {
const divideElement = Number(num1.value) / Number(num2.value);
resultElement.innerHTML = divideElement;
}
}
function subtraction() {
if (operatorElememt == "-") {
const subtractionElement = Number(num1.value) - Number(num2.value);
resultElement.innerHTML = subtractionElement;
}
}
<div class="container"></div>
<input class="num1" type="text">
<select name="" id="operator" class="operator">
<option data-operation value="-">-</option>
<option data-operation value="+">+</option>
<option data-operation value="/">/</option>
<option data-operation value="*">*</option>
</select>
<input class="num2" type="text">
<button onclick="summary();divide();multi();subtraction()">Click</button>
<br>
<span class="result_con">
<label for="" id="result"></label>
</span>
Console doesn't give any error code or any other result and I am quite new in to the subject. I was expecting a result regarding the selected operation. To select the operation I wrote select section and added the operations. I inteed to keep select part. Thanks in advance
I understand that you are a beginner. There were quiet a few issues with your code. I am attaching the snippet of the changes I made (I wouldn't consider myself an expert either and still may have overlooked something)
<body>
<div class="container"></div>
<input id="num1" type="text">
<select name="" id="operator" class="operator">
<option data-operation value="-">-</option>
<option data-operation value="+">+</option>
<option data-operation value="/">/</option>
<option data-operation value="*">*</option>
</select>
<input id="num2" type="text">
<button onclick="summary();divide();multi();subtraction()">Click</button>
<br>
<span class="result_con">
<label for="" id="result"></label>
</span>
<script>
const num1Element = document.querySelector("#num1");
const num2Element = document.querySelector("#num2");
const resultElement = document.querySelector("#result");
const operatorElememt = document.querySelector("#operator")
function summary() {
if (operatorElememt.value == "+") {
console.log("Adding");
const sumElement = Number(num1Element.value) + Number(num2Element.value);
resultElement.innerHTML = sumElement;
}
}
function multi() {
if (operatorElememt.value == "*") {
const multiElement = Number(num1Element.value) * Number(num2Element.value);
resultElement.innerHTML = multiElement;
}
}
function divide() {
if (operatorElememt.value == "/") {
const divideElement = Number(num1Element.value) / Number(num2Element.value);
resultElement.innerHTML = divideElement;
}
}
function subtraction() {
if (operatorElememt.value == "-") {
const subtractionElement = Number(num1Element.value) - Number(num2Element.value);
resultElement.innerHTML = subtractionElement;
}
}
</script>
</body>
Here are the issues I found:
You are trying to access your input element using a CSS selector for ids but you did not give those elements an id attribute
The select element works like an input element except it has a dropdown and limited options. You just need to get the select element like you would get an input Element. This also includes calling operatorElement.value
You are missing an E when getting the select element :)
And I would suggest instead of different functions, nest your conditions inside one event handler
Currently I am building a website which this page uses an external javascript file, one of the main function is that in the form if the user does not enter anything or enter the wrong value and clicks on the submit button, a error message will show up above each section, but unfortunately mine when I click on the submit button it will still submit and will not show any error, I suspect that the Javascript file is not linked properly but I did set the path correctly as you can see in the picture and the on the HTML page.
HTML File:
<meta charset="utf-8" />
<meta name="description" content="Demonstrates some basic HTML content elements and CSS" />
<meta name="keywords" content="html, css" />
<meta name="author" content="Jordan Siow" />
<link rel = "stylesheet" type = "text/css" href = "styles/style.css"/>
<script type="text/JavaScript" src="scripts/apply.js"></script>
<title>Apply </title>
<section class="front_title">
<p> Company XIT <img src="styles/images/logo.png" alt="logo" height="70" width="250"/>
</p>
</section>
<section class="topnav">
<table>
<tr>
<td >
Main
</td>
<td >
Jobs
</td>
<td id="current">
Apply
</td>
<td>
About
</td>
<td>
Enhancements
</td>
</tr>
</table>
</section>
<section id="style_apply">
<h2>Submit your Application!</h2>
<form method="post" id="apply_form" action="https://mercury.swin.edu.au/it000000/formtest.php">
<p><span id="job_id_error" class="error"></span></p>
<p><label for="jobid">Job Reference Number</label>
<input type="text" name="jobid" id="jobid" maxlength="5" pattern="[0-9]{5}" /></p>
<p><span id="firstname_error" class="error"></span></p>
<p><label for="firstname">First Name</label>
<input type ="text" name="First Name" id="firstname" maxlength="20" pattern="[a-zA-Z]+" /></p>
<p><span id="lastname_error" class="error"></span></p>
<p><label for="lastname">Last Name</label>
<input type ="text" name="Last Name" id="lastname" maxlength="20" pattern="[a-zA-Z]+" /></p>
<br/>
<p><span id="dob_error" class="error"></span></p>
<p><label for="dateofbirth">Date of Birth</label>
<input type="date" name="Date of Birth" id="dateofbirth" /></p>
<br/>
<br/>
<label>Gender</label>
<p><span id="gender_error" class="error"></span></p>
<fieldset id="gender">
<label for="male">Male</label>
<input type="radio" id="male" name="Gender" value="male" />
<label for="female">Female</label>
<input type="radio" id="female" name="Gender" value="female"/>
<label for="other">Others</label>
<input type="radio" id="other" name="Gender" value="other"/>
<label for="rathernotsay">Rather Not Say</label>
<input type="radio" id="rathernotsay" name="Gender" value="rathernotsay"/>
</fieldset>
<br/>
<div id="fieldset_label">
<label>Address Information</label>
</div>
<fieldset>
<p><span id="streetaddress_error" class="error"></span></p>
<p><label for="streetaddress">Street address</label>
<input type="text" name="Address" id="streetaddress" maxlength="40" "/></p>
<p><span id="suburb_error" class="error"></span></p>
<p><label for="suburb">Suburb/town</label>
<input type="text" name= "Suburb" id="suburb" maxlength="40" /></p>
<p><span id="state_error" class="error"></span></p>
<p><label for="state">State</label>
<select id="state" name="State">
<option value="">Please select</option>
<option value="VIC">VIC</option>
<option value="NSW">NSW</option>
<option value="QLD">QLD</option>
<option value="NT">NT</option>
<option value="WA">WA</option>
<option value="SA">SA</option>
<option value="TAS">TAS</option>
<option value="ACT">ACT</option>
</select></p>
<p><span id="postcodr_error" class="error"></span></p>
<p><label for="postcode">Postcode</label>
<input type="text" name= "Postcode" id="postcode" maxlength="4" pattern="\d{4}" placeholder="Postcode"/></p>
</fieldset>
<br/>
<p><span id="email_error" class="error"></span></p>
<p><label for="email">Email</label>
<input type="text" name="Email Address" id="email" /></p>
<p><span id="phonenumber_error" class="error"></span></p>
<p><label for="phonenumber">Phone Number</label>
<input type="text" name="Phone Number" id="phonenumber" maxlength="12" pattern="[0-9]{8-12}" ></p>
<label>Skill list</label>
<fieldset>
<p><span id="skill_error" class="error"></span></p>
<label for="skill1">Web development languages</label>
<input type="checkbox" id="skill1" name="Skill 1" value="skill"/>
<label for="skill2">Data Management abilities</label>
<input type="checkbox" id="skill2" name="Skill 2" value="skill"/>
<label for="skill3">Others</label>
<input type="checkbox" id="skill3" name="Other" value="skill"/>
<br/>
<br/>
<section>
<label for="comm" style="display:block">Other skillset</label>
<textarea class="comments" id="comm" name="Comments" rows="5" cols="50" placeholder="Other skillsets..."></textarea>
</section>
</fieldset>
<br/>
<br/>
<br/>
<br/>
<br/>
<div class="align_center">
<p><span id="error_check" class="error"></span></p>
<input type="submit" value="Submit Application"/>
<input type="reset" value="Reset Application form"/>
</div>
</form>
</section>
<br/>
<br/>
<br/>
<br/>
<footer class = "footer_text">
<hr/>
<p>
<strong>©</strong>
<a class="footer_text" href="http://www.swinburne.edu.au/">
Swinburne Universty of Technology
</a>
</p>
<p>
<strong>Done by:</strong> <a class="footer_text" href="mailto:103173691#student.swin.edu.au">
Jordan Siow</a>
</p>
</footer>
JS File:
/* To Validate the Form */
function validate(){
// Initialises the result variable
var result = true;
// Intialises the error tags
var job_id_error = document.getElementById("job_id_error");
job_id_error.innerHTML = "";
var firstname_error = document.getElementById("firstname_error");
firstname_error.innerHTML = "";
var lastname_error = document.getElementById("lastname_error");
lastname_error.innerHTML = "";
var dob_error = document.getElementById("dob_error");
dob_error.innerHTML = "";
var gender_error = document.getElementById("gender_error");
gender_error.innerHTML = "";
var streetaddress_error = document.getElementById("streetaddress_error");
streetaddress_error.innerHTML = "";
var suburb_error = document.getElementById("suburb_error");
suburb_error.innerHTML = "";
var state_error = document.getElementById("state_error");
state_error.innerHTML = "";
var postcode_error = document.getElementById("postcode_error");
postcode_error.innerHTML = "";
var email_error = document.getElementById("email_error");
email_error.innerHTML = "";
var phonenumber_error = document.getElementById("phonenumber_error");
phonenumber_error.innerHTML = "";
var skill_error = document.getElementById("skill_error");
skill_error.innerHTML = ""
// If there is an error in the input it will set the result to false and displays an error message
// To get the variables from the form and will chgeck the given rules
var jobid = document.getElementById("jobid").value;
if (jobid == ""){
job_id_error.innerHTML = "Job Reference Number must not be blank";
result = false;
}
var firstname = document.getElementById("firstname").value;
if (!firstname.match(/^[a-zA-Z]+$/) || firstname.value == ""){
firstname_error.innerHTML = "First name must only contain alphabetic characters";
alert("First name must only contain alphabetic characters")
result = false;
}
var lastname = document.getElementById("lastname").value;
if (!lastname.match(/^[a-zA-Z\-]+$/) || lastname.value == ""){
lastname_error.innerHTML = "Last name must only contain aphabetic characters";
result = false;
}
var dateofbirth = document.getElementById("dateofbirth").value;
if (!dateofbirth.match(/\d{2}\/\d{2}\/\d{4}/)){
dob_error.innerHTML = "Invalid Date of Birth";
result = false;
}
var age = calculate_age(dateofbirth);
if (!isFinite(age) || isNaN(age)) {
dob_error.innerHTML = "Your Date of Birth role is not Available.";
result = false;
}
else if (age < 21 || age > 70) {
dob_error.innerHTML =
"You must be between 21 and 70 years old to apply.";
result = false;
}
var male = document.getElementById("male").checked;
var female = document.getElementById("female").checked;
var other = document.getElementById("other").checked;
var rathernotsay = document.getElementById("rathernotsay").checked;
if (!(male || female || other || rathernotsay)) {
gender_error.innerHTML = "Please select a gender.";
result = false;
}
var streetaddress = document.getElementById("streetaddress").value;
if (streetaddress == "") {
streetaddress_error.innerHTML = "You must enter a street address.";
result = false;
}
var suburb = document.getElementById("suburb").value;
if (suburb == "") {
suburb_error.innerHTML = "You must enter a suburb or town";
result = false;
}
var postcode = Number(document.getElementById("postcode").value);
if (postcode == "") {
postcode_error.innerHTML = "You must select a postcode";
result = false;
}
var state = document.getElementById("state").value
if (state == "") {
state_error.innerHTML = "You must select a state";
result = false;
} else {
var tempMsg = validate_postcode(state, postcode);
if (tempMsg != "") {
state_error.innerHTML = tempMsg;
result = false;
}
}
var email = document.getElementById("email").value;
if (email == "") {
email_error.innerHTML = "You must enter an email address";
result = false;
}
var phonenumber = document.getElementById("phonenumber").value;
if (phonenumber == "") {
phonenumber_error.innerHTML = "You must enter a phone number";
result = false;
}
if (result){
storeBooking(firstname, lastname, dateofbirth, male, female, other, rathernotsay, streetaddress, suburb, state, postcode, email, phonnumber)
}
if (!result) {
document.getElementById("error_check").innerHTML = "Please correct all of the errors given above.";
}
return result;
}
/**
* calcualte age from date of birth
*/
function calculate_age(dateofbirth) {
var today = new Date();
var DateOfBirth = new Date(dateofbirth);
// get the difference between the years
var age = today.getFullYear() - DateOfBirth.getFullYear();
// get the difference between the months
var month = today.getMonth() - DateOfBirth.getMonth();
// if the dateofbirth month and day is earlier in the year
if (month < 0 || (month === 0 && today.getDate() < DateOfBirth.getDate())) {
age--; // remove a year
}
return age;
}
function validate_postcode(state, postcode) {
var errMsg = "";
switch (state) {
case "vic":
if (!((postcode >= 3000 && postcode <= 3999) || (postcode >= 8000 && postcode <= 8999))) {
errMsg += "Post Code not in Victoria.";
}
break;
case "nsw":
if (!((postcode >= 1000 && postcode <= 2599) || (postcode >= 2619 && postcode <= 2899) || (postcode >= 2921 && postcode <= 2999))) {
errMsg += "Post Code not in New South Wales.";
}
break;
case "qld":
if (!((postcode >= 4000 && postcode <= 4999) || (postcode >= 9000 && postcode <= 9999))) {
errMsg += "Post Code not in Queensland.";
}
break;
case "nt":
if (!(postcode >= 800 && postcode <= 999)) {
errMsg += "Post Code not in Northern Territory.";
}
break;
case "wa":
if (!(postcode >= 6000 && postcode <= 6999)) {
errMsg += "Post Code not in Western Australia.";
}
break;
case "sa":
if (!(postcode >= 5000 && postcode <= 5999)) {
errMsg += "Post Code not in Southern Australia.";
}
break;
case "tas":
if (!(postcode >= 7000 && postcode <= 7999)) {
errMsg += "Post Code not in Tasmania.";
}
break;
case "act":
if (!((postcode >= 200 && postcode <= 299) || (postcode >= 2600 && postcode <= 2618) || (postcode >= 2900 && postcode <= 2920))) {
errMsg += "Post Code not in Australian Capital Territory.";
}
break;
default:
errMsg = "Post Code not Valid.";
}
return errMsg;
}
/**
* Prefill the form from exisitng session data
*/
function prefill_id() {
var jobId_input = document.getElementById("jobid");
if (localStorage.jobId != undefined) {
// hidden input to submit details
jobId_input.value = localStorage.jobId;
jobId_input.readOnly = true;
} else {
jobId_input.readOnly = false;
}
}
/**
* Prefill the form from exisitng session data
*/
function prefill_form() {
prefill_id();
if (sessionStorage.firstname != undefined) {
document.getElementById("firstname").value = sessionStorage.firstname;
document.getElementById("lastname").value = sessionStorage.lastname;
document.getElementById("dateofbirth").value = sessionStorage.dateofbirth;
document.getElementById("streetaddress").value = sessionStorage.streetaddress;
document.getElementById("suburb").value = sessionStorage.suburb;
document.getElementById("state").value = sessionStorage.state;
document.getElementById("postcode").value = sessionStorage.postcode;
document.getElementById("email").value = sessionStorage.email;
document.getElementById("phonenumber").value = sessionStorage.phonenumber;
switch (sessionStorage.gender) {
case "male":
document.getElementById("male").checked = true;
break;
case "female":
document.getElementById("female").checked = true;
break;
case "other":
document.getElementById("other").checked = true;
break;
case "rathernotsay":
document.getElementById("rathernotsay").checked = true;
break;
}
var skills = sessionStorage.skills;
document.getElementById("skill1").checked = skills.includes("skill1");
document.getElementById("skill2").checked = skills.includes("skill2");
document.getElementById("skill3").checked = skills.includes("skill3");
}
}
/**
* Store Job ID for pre fill in application form
*/
function storeJobId1() {
localStorage.jobId = document.getElementById("job1_id").innerHTML;
}
function storeJobId2() {
localStorage.jobId = document.getElementById("job2_id").innerHTML;
}
/**
* Store values for session
*/
function storeBooking(skill1, skill2, skill3, comm, firstname,
lastname, dateofbirth, streetaddress, suburb, state, postcode, email, phonenumber, male, female, other) {
// store values in sessionStorage
var skill_string = "";
if (skill1) {
skill_string = "skill1";
}
if (skill2) {
if (skill_string != "") {
skill_string += ", ";
}
skill_string += "skill2";
}
if (skill3) {
if (skill_string != "") {
skill_string += ", ";
}
skill_string += "skill3";
}
sessionStorage.skills = skill_string;
sessionStorage.firstname = firstname;
sessionStorage.lastname = lastname;
sessionStorage.dateofbirth = dateofbirth;
sessionStorage.streetaddress = streetaddress;
sessionStorage.suburb = suburb;
sessionStorage.state = state;
sessionStorage.postcode = ;
sessionStorage.email = email;
sessionStorage.phonenumber = phonenumber;
sessionStorage.comm = comm;
if (male) {
sessionStorage.gender = "male";
} else if (female) {
sessionStorage.gender = "female";
} else if (other) {
sessionStorage.gender = "other";
} else if (rathernotsay) {
sessionStorage.gender = "rathernotsay";
}
}
/*
This function is called when the browser window loads
it will register functions that will respond to browser events
*/
function init() {
if (document.title == "Available Jobs") {
document.getElementById("job1_apply").onclick = storeJobId1;
document.getElementById("job2_apply").onclick = storeJobId2;
} else if (document.title == "Application Form") {
prefill_form();
// register the event listener to the form
document.getElementById("apply_form").onsubmit = validate;
document.getElementById("apply_form").onreset = function () {
localStorage.clear();
prefill_id();
;}
}
}
window.onload = init;
I think you should check out this article: preventDefault() Event Method
When clicked, you should prevent the default behavior.
<script type="text/JavaScript" src="scripts/apply.js"></script>
Add the above script tag just before closing of body tag, it it best practice.
put a console.log("js file linked"); inside js file to test whether its linked or not.
Feel free to ask if it didn't work...
In the comments you mentioned
my friend told me its got to do with the last line in the js file "window.onload = init();
Your friend is correct - not sure if this is the only relevant thing, but here you are first running the function init() and the return value of that function is being saved into window.onload. Check out this example code:
function init() {
console.log(document.readyState);
}
window.onload = init();
console.log("Window onload is", window.onload);
Here init is run immediately and the return value of init will be saved to window.onload. This prints
loading
apply.js:315 Window onload is null
Instead, you should add a reference to the init function, so that the value of window.onload is your init function itself, not the return value; so the correction would be
function init() {
console.log(document.readyState);
}
window.onload = init;
console.log("Window onload is", window.onload);
// this one prints out
// Window onload is ƒ init() {console.log(document.readyState);}
// apply.js:311 complete
The "document.readyState" is used to check if the document has been loaded and parsed.
Before you guys shoot me down for not trying the code, I am very new to Javascript and I need to implement this function into a very important work.
I got the basis dropdown calculation from this thread, Javascript drop-down form math calculation. I modified the code referred from the thread for my codes
Forgive me if my codes is totally wrong, I am still trying to do piece by piece. Will be grateful if you all can help me pinpoint the errors and/or issues.
So back to topic, I want to get the cost for each items, and then count the total cost to be calculated. The JSFiddle link is here. Appreciate for your helps rendered.
HTML CODES
<form name="priceCalc" action="">Laundry (Gentlemen)
<br/>Apparels:
<select name="gapparell" onchange="gentlemanl();">
<option value="5.00">Tie</option>
<option value="7.50">Shirt</option>
<option value="12.50">Jacket</option>
</select>
<br>Quantity:
<input type="text" id="gqtyl" onchange="gentlemanl();" />
<br>
<br/>Dry Cleaning (Gentlemen)
<br/>Apparels:
<select name="gappareld" onchange="gentlemand();">
<option value="6.00">Tie</option>
<option value="8.50">Shirt</option>
<option value="13.50">Jacket</option>
</select>
<br>Quantity:
<input type="text" id="gqtyd" onchange="gentlemand();" />
<br/><br/><br/>Laundry (Ladies)
<br/>Apparels:
<select name="lapparell" onchange="ladiesl();">
<option value="5.00">Tie</option>
<option value="7.50">Shirt</option>
<option value="12.50">Jacket</option>
</select>
<br>Quantity:
<input type="text" id="lqtyl" onchange="ladiesl();" />
<br>
<br/>Dry Cleaning (Ladies)
<br/>Apparels:
<select name="lappareld" onchange="ladiesd();">
<option value="6.00">Tie</option>
<option value="8.50">Shirt</option>
<option value="13.50">Jacket</option>
</select>
<br>Quantity:
<input type="text" id="lqtyd" onchange="ladiesd();" />
<br>Total Cost:
<input type="text" id="prices">
<br/>
<input type="button" value="Figure out pricing!" onclick="total();">
<br>
JAVASCRIPT CODES
function gentlemanl() {
var Amt = document.priceCalc.gapparell;
var Qty = document.priceCalc.gqtyl;
var price = parseInt(Qty.value) * parseFloat(Amt.value);
document.getElementById("prices").value = price;
}
function gentlemand() {
var Amt = document.priceCalc.gappareld;
var Qty = document.priceCalc.gqtyd;
var price = parseInt(Qty.value) * parseFloat(Amt.value);
document.getElementById("prices").value = price;
}
function ladiesl() {
var Amt = document.priceCalc.lapparell;
var Qty = document.priceCalc.lqtyl;
var price = parseInt(Qty.value) * parseFloat(Amt.value);
document.getElementById("prices").value = price;
}
function ladiesd() {
var Amt = document.priceCalc.lappareld;
var Qty = document.priceCalc.lqtyd;
var price = parseInt(Qty.value) * parseFloat(Amt.value);
document.getElementById("prices").value = price;
}
function total() {
//I am not sure how the function works
}
this is a working exemple of what i think you want to do : http://jsfiddle.net/gd12k4mt/5/
function gentleman1() {
var Amt = document.priceCalc.gapparell;
var Qty = document.priceCalc.gqtyl;
return parseInt(Qty.value) * parseFloat(Amt.value);
}
I designed the functions like that. With a return statement for the value of each product * the quantity.
function total() {
if(isNaN(gentleman1())) {
gentleman_laundry = 0;
} else {
gentleman_laundry = gentleman1();
}
if(isNaN(gentlemand())) {
gentleman_dry = 0;
} else {
gentleman_dry = gentlemand();
}
if(isNaN(ladies1())) {
ladies_laundry = 0;
} else {
ladies_laundry = ladies1();
}
if(isNaN(ladiesd())){
ladies_dry = 0;
} else {
ladies_dry = ladiesd();
}
var totalPrice = gentleman_laundry+gentleman_dry+ladies_laundry+ladies_dry;
document.getElementById('prices').value = totalPrice;
}
The total function is like that with a test on empty fields. In this purpose I created the variables :
var gentleman_laundry,
gentlemend_dry,
ladies_laundry,
ladies_dry;
Be sure that your functions's name is good : here you have two different names in you're html events and in your script.
I personally did without theses html listeners because we want the total price at the end I guess. So I declared only one listener on the final button.
document.getElementById('submit_button').addEventListener('click', function(){
total();
})
Hope this helped.
You can try like this,
HTML
<form name="priceCalc" action="">Laundry (Gentlemen)
<br/>Apparels:
<select id="gapparell" />
<option value="5.00">Tie</option>
<option value="7.50">Shirt</option>
<option value="12.50">Jacket</option>
</select>
<br>Quantity:
<input type="text" id="gqtyl" />
<br>
<br/>Dry Cleaning (Gentlemen)
<br/>Apparels:
<select id="gappareld">
<option value="6.00">Tie</option>
<option value="8.50">Shirt</option>
<option value="13.50">Jacket</option>
</select>
<br>Quantity:
<input type="text" id="gqtyd" />
<br/>
<br/>
<br/>Laundry (Ladies)
<br/>Apparels:
<select id="lapparell" >
<option value="5.00">Tie</option>
<option value="7.50">Shirt</option>
<option value="12.50">Jacket</option>
</select>
<br>Quantity:
<input type="text" id="lqtyl"/>
<br>
<br/>Dry Cleaning (Ladies)
<br/>Apparels:
<select id="lappareld" onchange="ladiesd();">
<option value="6.00">Tie</option>
<option value="8.50">Shirt</option>
<option value="13.50">Jacket</option>
</select>
<br>Quantity:
<input type="text" id="lqtyd" onchange="ladiesd();" />
<br>Total Cost:
<input type="text" id="prices">
<br/>
<input type="button" value="Figure out pricing!" onclick="total()">
<br>
</form>
This is JS,
function gentleman1() {
var price=0;
var e = document.getElementById('gapparell')
var Amt = e.options[e.selectedIndex].value;
var Qty = document.getElementById('gqtyl').value;
price = parseInt(Qty) * parseFloat(Amt);
return (isNaN(price)) ? 0 : price;
//document.getElementById("prices").value = price;
}
function gentlemand() {
var price=0;
var e = document.getElementById('gappareld')
var Amt = e.options[e.selectedIndex].value;
var Qty = document.getElementById('gqtyd').value;
price = parseInt(Qty) * parseFloat(Amt);
return (isNaN(price)) ? 0 : price;
}
function ladies1() {
var price=0;
var e = document.getElementById('lapparell')
var Amt = e.options[e.selectedIndex].value;
var Qty = document.getElementById('lqtyl').value;
price = parseInt(Qty) * parseFloat(Amt);
return (isNaN(price)) ? 0 : price;
}
function ladiesd() {
var price=0;
var e = document.getElementById('lappareld')
var Amt = e.options[e.selectedIndex].value;
var Qty = document.getElementById('lqtyd').value;
price = parseInt(Qty) * parseFloat(Amt);
return (isNaN(price)) ? 0 : price;
}
function total() {
var price=gentleman1()+gentlemand()+ladiesd()+ladiesd();
document.getElementById('prices').value=price;
}
Working Demo
I'm trying to get it where a whole two paragraph div can be drawn onto a canvas. I'm mostly having problems with getting the div on a canvas without having to use all of the canvas tags and draw out every line. I think this is possible, let me know if it isn't. I'm intermediate with Javascript and Php, experienced with HTML, but new to canvas so try to keep it simple.
HTML Code:
<head>
<meta http-equiv="content-type" content="text/xml; charset=utf-8" />
<title>Quote It!</title>
<link rel = "stylesheet"
type = "text/css"
href = "passext.css" />
<script type = "text/javascript" src = "js2.js"></script>
</head>
<body>
<h1>It's as easy as One...Two...Three!</h1>
<div id = "instructions">
<p style = "text-align:center;">Instructions:</p>
<ol>
<li>Fill out quote and author fields, then press "Create Quote".</li>
<li>Adjust attributes and watch as it updates in real-time!</li>
<li>Click save and it will convert to a versatile image.</li>
</ol>
</div>
<div id = "tips_warnings">
<p style = "text-align:center;">Tips & Warnings:</p>
<ul>
<li>Don't forget to add quotation marks!</li>
<li>Don't forget a dash before the author.</li>
<li>To create a new quote, hit "Reset", and fill out the form.</li>
</ul>
</div>
<form name = "personalize" id = "personalize">
<fieldset class = "person">
<legend class = "legend">Personalize</legend>
<p>
<label class = "uinfo">Quote (One you make up or one you know):</label>
</p>
<p>
<textarea id = "quote"
rows = "10"
cols = "45"></textarea>
</p>
<p>
<label class = "uinfo">Author:</label>
<input type="text"
id = "write_author"
name = "author"
value = "eg. (-Billy Joe)"
onclick = "this.value = ''"/>
</p>
<p>
<label class = "uinfo">Text Color:</label>
<select id = "selColor" onchange="myFunction()">
<option value = "#ffffff">White</option>
<option value = "#000000">Black</option>
<option value = "#f09dee">Pink</option>
<option value = "#ff0000">Red</option>
<option value = "#1e4d0c">Green</option>
<option value = "#00ff00">Neon Green</option>
<option value = "#0000ff">Blue</option>
<option value = "#00ffff">Cyan</option>
<option value = "#ff00ff">Magenta</option>
<option value = "#ffff00">Yellow</option>
<option value = "#cccccc">Grey</option>
</select>
</p>
<p>
<label class = "uinfo">Text Style:</label>
<select id = "selStyle" onchange = "myFunction()">
<option value = "default">None</option>
<option value = "italic">Italics</option>
<option value = "underline">Underline</option>
<option value = "bold">Bold</option>
</select>
</p>
<p>
<label class = "uinfo">Background Color:</label>
<select id = "selBack" onchange = "myFunction()">
<option value = "null">None</option>
<option value = "#000000">Black</option>
<option value = "#ff0000">Red</option>
<option value = "#00ff00">Green</option>
<option value = "#0000ff">Blue</option>
<option value = "#00ffff">Cyan</option>
<option value = "#ff00ff">Magenta</option>
<option value = "#ffff00">Yellow</option>
<option value = "#ffffff">White</option>
<option value = "#cccccc">Grey</option>
</select>
</p>
<p>
<label class = "uinfo">Border:</label>
<select id = "selBorder" onchange="myFunction()">
<option value = "none">None</option>
<option value = "solid">Solid</option>
<option value = "double">Double</option>
<option value = "groove">Groove</option>
<option value = "ridge">Ridge</option>
<option value = "inset">Inset</option>
<option value = "outset">Outset</option>
<option value = "dashed">Dashed</option>
<option value = "dotted">Dotted</option>
</select>
</p>
<p>
<label class = "uinfo">Border Width:</label>
<select id = "selWidth" onchange = "myFunction()">
<option value = "500px">Large</option>
<option value = "375px">Medium</option>
<option value = "250px">Small</option>
</select>
</p>
<p>
<label class = "uinfo">Font:</label>
<select id = "selFont" onchange = "myFunction()">
<option value = "Times New Roman">Times New Roman</option>
<option value = "Serif">Serif</option>
<option value = "Sans-Serif">Sans Serif</option>
<option value = "Fantasy">Fantasy</option>
<option value = "Monospace">Monospace</option>
<option value = "Cursive">Cursive</option>
</select>
</p>
<p>
<label class = "uinfo">Font Size:</label>
<select id = "selSize" onchange = "myFunction()">
<option value = "105%">13pt</option>
<option value = "120%">14pt</option>
<option value = "130%">15pt</option>
<option value = "140%">16pt</option>
<option value = "150%">18pt</option>
</select>
</p>
<p class = "create_quote">
<input type = "button"
value = "Create Quote"
onclick = "myFunction()"/>
<script type = "text/javascript" src = "js2.js"></script>
<input type = "reset"/>
</p>
</fieldset>
</form>
<canvas id = "blank">
<p id = "blank1"></p>
<p id = "author"></p>
</canvas>
<input type = "button"
id = "save"
value = "Save"
onclick = "saveFuction()"/>
<script type = "text/javascript" src = "js2.js"></script>
</body>
</html>
Javascript Code:
function myFunction(){
var quote, quote1, fsize, fsize1, fColor, fcolor1, bcolor, bcolor1, font, font1, width, width1, border, border1, author, author1, author2, format, fstyle, fstyle1;
format = document.getElementById("blank");
var context = format.getContext("2d");
quote=document.getElementById("quote");
quote1=quote.value;
outPut = document.getElementById("blank1");
if (quote1 != "") {
outPut.innerHTML = quote1;
} else {
alert("You need to enter a quote!");
}
author = document.getElementById("write_author");
author1 = author.value;
author2 = document.getElementById("author")
if (author1 == "" || author1 == "eg. (-Billy Joe)") {
alert("Who wrote this?");
} else {
author2.innerHTML = author1;
}
fcolor = document.getElementById("selColor");
fcolor1 = fcolor.value;
format.style.color=(fcolor1);
fstyle = document.getElementById("selStyle");
fstyle1 = fstyle.value;
if (fstyle1 == "italic") {
format.style.fontStyle=("italic");
format.style.textDecoration=("");
format.style.fontWeight=("");
} else if (fstyle1 == "underline"){
format.style.textDecoration=("underline");
format.style.fontStyle=("");
format.style.fontWeight=("");
} else if (fstyle1 == "bold") {
format.style.fontWeight=("bold");
format.style.textDecoration=("");
format.style.fontStyle = ("");
} else if (fstyle1 == "default") {
format.style.fontWeight=("");
format.style.textDecoration=("");
format.style.fontStyle = ("");
}
bcolor = document.getElementById("selBack");
bcolor1 = bcolor.value;
format.style.backgroundColor=(bcolor1);
border = document.getElementById("selBorder");
border1 = border.value;
format.style.border=( border1);
if (border1 == "dashed") {
format.style.borderWidth=("3px");
} else {
format.style.borderWidth=("5px");
}
width = document.getElementById("selWidth");
width1 = width.value;
format.style.width=(width1);
if (width1 == "375px") {
document.getElementById("blank").style.position = "absolute";
document.getElementById("blank").style.left = "962.5px";
}else if (width1 == "250px") {
document.getElementById("blank").style.position = "absolute";
document.getElementById("blank").style.left = "1025px";
}else if (width1 == "500px") {
document.getElementById("blank").style.position = "absolute";
document.getElementById("blank").style.left = "900px";
}
font = document.getElementById("selFont");
font1 = font.value;
format.style.fontFamily=(font1);
fsize = document.getElementById("selSize");
fsize1 = fsize.value;
format.style.fontSize=(fsize1);
}
function saveFunction(){
format.location.href = format.toDataURL();
}
Any help would be appreciated.
You can't draw html elements directly on canvas.
You'll have to learn/use the canvas drawing commands.
However, some people have had success with this library that simulates html elements on canvas:
http://html2canvas.hertzen.com/
You might also want to know that canvas.toDataURL doesn't allow you to save the image data to a user's local file system for security reasons.
Alternatively,
There are many screen-grabbers out there. SnagIt is a good one: http://www.techsmith.com/snagit.html
Check out html2Canvas as markE said, it takes a dom element and converts it to a canvas, and then you can draw that canvas onto another canvas something like this:
http://html2canvas.hertzen.com/
var domElement = document.getElementById('myElementId');
html2canvas(domElement, {
onrendered: function (domElementCanvas) {
var canvas = document.createElement('canvas');
canvas.getContext('2d').drawImage(domElementCanvas, 0, 0, 100, 100);
// do something with canvas
}
}
I'm attempting to create a page that creates a div with two paragraphs, specifically a quote and author. Afterwards, the user can change things like background color, font, font-size, and other attributes. So far everything works good, but then I want to have a save button that turns the div into one image that the user can right-click and save the image. Examples like this include http://www.teacherfiles.com/free_word_art.html and http://cooltext.com/. I looked into some of the script and HTML, but it led me to a dead end. Maybe somebody else can get something out of those? Then I started searching and saw a lot of different answers involving canvas, which I'm new to.
HTML Code:
<head>
<meta http-equiv="content-type" content="text/xml; charset=utf-8" />
<title>Quote It!</title>
<link rel = "stylesheet"
type = "text/css"
href = "passext.css" />
<script type = "text/javascript" src = "js2.js"></script>
</head>
<body>
<h1>It's as easy as One...Two...Three!</h1>
<div id = "instructions">
<p style = "text-align:center;">Instructions:</p>
<ol>
<li>Fill out quote and author fields, then press "Create Quote".</li>
<li>Adjust attributes and watch as it updates in real-time!</li>
<li>Click save and it will convert to a versatile image.</li>
</ol>
</div>
<div id = "tips_warnings">
<p style = "text-align:center;">Tips & Warnings:</p>
<ul>
<li>Don't forget to add quotation marks!</li>
<li>Don't forget a dash before the author.</li>
<li>To create a new quote, hit "Reset", and fill out the form.</li>
</ul>
</div>
<form name = "personalize" id = "personalize">
<fieldset class = "person">
<legend class = "legend">Personalize</legend>
<p>
<label class = "uinfo">Quote (One you make up or one you know):</label>
</p>
<p>
<textarea id = "quote"
rows = "10"
cols = "45"></textarea>
</p>
<p>
<label class = "uinfo">Author:</label>
<input type="text"
id = "write_author"
name = "author"
value = "eg. (-Billy Joe)"
onclick = "this.value = ''"/>
</p>
<p>
<label class = "uinfo">Text Color:</label>
<select id = "selColor" onchange="myFunction()">
<option value = "#ffffff">White</option>
<option value = "#000000">Black</option>
<option value = "#f09dee">Pink</option>
<option value = "#ff0000">Red</option>
<option value = "#1e4d0c">Green</option>
<option value = "#00ff00">Neon Green</option>
<option value = "#0000ff">Blue</option>
<option value = "#00ffff">Cyan</option>
<option value = "#ff00ff">Magenta</option>
<option value = "#ffff00">Yellow</option>
<option value = "#cccccc">Grey</option>
</select>
</p>
<p>
<label class = "uinfo">Text Style:</label>
<select id = "selStyle" onchange = "myFunction()">
<option value = "default">None</option>
<option value = "italic">Italics</option>
<option value = "underline">Underline</option>
<option value = "bold">Bold</option>
</select>
</p>
<p>
<label class = "uinfo">Background Color:</label>
<select id = "selBack" onchange = "myFunction()">
<option value = "null">None</option>
<option value = "#000000">Black</option>
<option value = "#ff0000">Red</option>
<option value = "#00ff00">Green</option>
<option value = "#0000ff">Blue</option>
<option value = "#00ffff">Cyan</option>
<option value = "#ff00ff">Magenta</option>
<option value = "#ffff00">Yellow</option>
<option value = "#ffffff">White</option>
<option value = "#cccccc">Grey</option>
</select>
</p>
<p>
<label class = "uinfo">Border:</label>
<select id = "selBorder" onchange="myFunction()">
<option value = "none">None</option>
<option value = "solid">Solid</option>
<option value = "double">Double</option>
<option value = "groove">Groove</option>
<option value = "ridge">Ridge</option>
<option value = "inset">Inset</option>
<option value = "outset">Outset</option>
<option value = "dashed">Dashed</option>
<option value = "dotted">Dotted</option>
</select>
</p>
<p>
<label class = "uinfo">Border Width:</label>
<select id = "selWidth" onchange = "myFunction()">
<option value = "500px">Large</option>
<option value = "375px">Medium</option>
<option value = "250px">Small</option>
</select>
</p>
<p>
<label class = "uinfo">Font:</label>
<select id = "selFont" onchange = "myFunction()">
<option value = "Times New Roman">Times New Roman</option>
<option value = "Serif">Serif</option>
<option value = "Sans-Serif">Sans Serif</option>
<option value = "Fantasy">Fantasy</option>
<option value = "Monospace">Monospace</option>
<option value = "Cursive">Cursive</option>
</select>
</p>
<p>
<label class = "uinfo">Font Size:</label>
<select id = "selSize" onchange = "myFunction()">
<option value = "105%">13pt</option>
<option value = "120%">14pt</option>
<option value = "130%">15pt</option>
<option value = "140%">16pt</option>
<option value = "150%">18pt</option>
</select>
</p>
<p class = "create_quote">
<input type = "button"
value = "Create Quote"
onclick = "myFunction()"/>
<script type = "text/javascript" src = "js2.js"></script>
<input type = "reset"/>
</p>
</fieldset>
</form>
<canvas id = "blank">
<p id = "blank1"></p>
<p id = "author"></p>
</canvas>
<input type = "button"
id = "save"
value = "Save"
onclick = "saveFuction()"/>
<script type = "text/javascript" src = "js2.js"></script>
</body>
</html>
Javascript Code:
function myFunction(){
var quote, quote1, fsize, fsize1, fColor, fcolor1, bcolor, bcolor1, font, font1, width, width1, border, border1, author, author1, author2, format, fstyle, fstyle1;
format = document.getElementById("blank");
var context = format.getContext("2d");
quote=document.getElementById("quote");
quote1=quote.value;
outPut = document.getElementById("blank1");
if (quote1 != "") {
outPut.innerHTML = quote1;
} else {
alert("You need to enter a quote!");
}
author = document.getElementById("write_author");
author1 = author.value;
author2 = document.getElementById("author")
if (author1 == "" || author1 == "eg. (-Billy Joe)") {
alert("Who wrote this?");
} else {
author2.innerHTML = author1;
}
fcolor = document.getElementById("selColor");
fcolor1 = fcolor.value;
format.style.color=(fcolor1);
fstyle = document.getElementById("selStyle");
fstyle1 = fstyle.value;
if (fstyle1 == "italic") {
format.style.fontStyle=("italic");
format.style.textDecoration=("");
format.style.fontWeight=("");
} else if (fstyle1 == "underline"){
format.style.textDecoration=("underline");
format.style.fontStyle=("");
format.style.fontWeight=("");
} else if (fstyle1 == "bold") {
format.style.fontWeight=("bold");
format.style.textDecoration=("");
format.style.fontStyle = ("");
} else if (fstyle1 == "default") {
format.style.fontWeight=("");
format.style.textDecoration=("");
format.style.fontStyle = ("");
}
bcolor = document.getElementById("selBack");
bcolor1 = bcolor.value;
format.style.backgroundColor=(bcolor1);
border = document.getElementById("selBorder");
border1 = border.value;
format.style.border=( border1);
if (border1 == "dashed") {
format.style.borderWidth=("3px");
} else {
format.style.borderWidth=("5px");
}
width = document.getElementById("selWidth");
width1 = width.value;
format.style.width=(width1);
if (width1 == "375px") {
document.getElementById("blank").style.position = "absolute";
document.getElementById("blank").style.left = "962.5px";
}else if (width1 == "250px") {
document.getElementById("blank").style.position = "absolute";
document.getElementById("blank").style.left = "1025px";
}else if (width1 == "500px") {
document.getElementById("blank").style.position = "absolute";
document.getElementById("blank").style.left = "900px";
}
font = document.getElementById("selFont");
font1 = font.value;
format.style.fontFamily=(font1);
fsize = document.getElementById("selSize");
fsize1 = fsize.value;
format.style.fontSize=(fsize1);
}
function saveFunction(){
format.location.href = format.toDataURL();
}
Any help would be appreciated.
Here is some stuff that you can use in your project. See the examples, it can be help. That script allows you to take "screenshots" of webpages or parts of it, directly on the users browser. I hope you make it.
http://html2canvas.hertzen.com/
and here some examples
http://experiments.hertzen.com/jsfeedback/