I want to implement a button which changes the background colour and text colour instantly. The colours are predefined in an array.
Code Snippet
<?php
include 'src/wordlist.php';
include 'src/colorcodes.php';
$result1 = $one[array_rand($one)] . " " . $two[array_rand($two)];
$colormix1 = $colors[array_rand($colors)];
$colormix2 = $colors[array_rand($colors)];
if ($colormix1 == $colormix2) {
$colormix2 = $colors[array_rand($colors)];
}
?>
<!DOCTYPE html>
<html>
<head>
</head>
<body style="background: <?php echo $colormix2; ?>;">
<div class="table_1">
<table>
<tr>
<th>
HEADER
</th>
</tr>
<tr>
<td>
<p style="color: <?php echo $colormix1; ?>;">» <?php echo $result1; ?>. «</p>
</td>
</tr>
</table>
</div>
</body>
</html>
How can I achieve this with only JavaScript?
Thanks in advance!
//EDIT:
I found a solution:
function changeBackground() {
var colormix1 = colorcodes[Math.floor(Math.random() * colorcodes.length)];
var colormix2 = colorcodes[Math.floor(Math.random() * colorcodes.length)];
if (colormix1 == colormix2) {
var colormix2 = colorcodes[Math.floor(Math.random() * colorcodes.length)];
}
document.getElementById("quote").style.color = colormix1;
document.getElementById("footer").style.background = colormix1;
document.getElementById("ft-button").style.backgroundColor = colormix1;
document.getElementById("ft-button").style.color = colormix2;
document.getElementById("background").style.background = colormix2;
}
</script>
By calling the elements by their Id it worked just fine.
It is fairly simple to achieve this in JS. Please refer DOM API for more details
Run this Code Snippet for a demo
function changeBackground(value) {
var bgElement = document.getElementsByClassName('background')[0];
var textElement = document.getElementsByClassName('text')[0];
if (bgElement) {
bgElement.style.background = value;
}
if (textElement) {
textElement.style.color = value;
}
}
.background {
width: 100vw;
height: 100vh;
background: #000;
}
.dropdown {
width: 150px;
height: 32px;
margin: 16px;
}
.text {
font-size: 16px;
color: #000;
margin: 16px;
}
<div class="text">
This is some text
</div>
<div class="background">
<select class="dropdown" onchange="changeBackground(value)">
<option value="#F44336">Red</option>
<option value="#E91E63">Pink</option>
<option value="#9C27B0">Purple</option>
<option value="#673AB7">Deep purple</option>
<option value="#3F51B5">Indigo</option>
<option value="#FFFFFF">White</option>
<option value="#000000">Black</option>
</select>
</div>
Related
I have a chess form with six fields. Two are drop down menus to select names (whiteplayername and blackplayername) and the other four can be used to add a custom name instead (firstnamewhite, lastnamewhite, firstnameblack, lastnameblack). Currently, I want my javascript to disable the custom fields if a name has been selected from the drop down menu (this is working). I also want the submit button to be disabled if neither the whiteplayername or firstnamewhite and blackplayername of firstnameblack is selected. Currently, the submit-button becomes enabled if a name is selected from both the blackplayername and whiteplayname menus but then does not become disabled again if an empty field is selected in either.
Edit
The full html is below, though I have taken out a section just made up of text and rows from the table in order to cut down on the space used.
<!DOCTYPE html>
<html lang="en"
xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>chessopenings3</title>
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
<style>
body {
style: "background-color: #FF0000;
}
.topnav {
position: relative;
overflow: hidden;
background-color: #333;
border: 2px;
width: max-content;
}
.topnav a {
float: left;
color: #f2f2f2;
text-align: center;
padding: 14px 16px;
text-decoration: none;
font-size: 17px;
border: 2px;
}
.topnav a:hover {
background-color: #ddd;
color: black;
border: 2px;
}
.formformat {
color: white;
padding: 50px;
font-size: 24px;
font-family: Arial, Helvetica, sans-serif;
}
.instructions-text {
position: absolute;
color: white;
align: center;
left: 750px;
top: 150px;
font-family: Arial, Helvetica, sans-serif;
font-size: 20px;
}
.warning {
position: absolute;
color: white;
text-align: left;
left: 150px;
top: 50px;
font-family: Arial, Helvetica, sans-serif;
font-size: 20px;
}
select {
width: 120px;
}
select:focus {
min-width: 120px;
width: auto;
}
#media screen and (max-width: 500px) {
.navbar a {
float: none;
display: block;
}
}
</style>
<script>
document.addEventListener("DOMContentLoaded", function () {
let isformvalid = false;
document.getElementById("submit-button").disabled = !isformvalid;
document.getElementById("whiteplayername").addEventListener("change", function () {
let blackplayername =
document.getElementById("blackplayername");
let firstnameblack =
document.getElementById("firstnameblack");
let firstnamewhite =
document.getElementById("firstnamewhite");
let lastnamewhite =
document.getElementById("lastnamewhite");
let lastnameblack =
document.getElementById("lastnameblack");
disablewhenmandatorynamemissingwhitename(this.value, blackplayername, firstnameblack, firstnamewhite, lastnameblack, lastnamewhite);
isformvalid = checkeitherfirstorfullnamepopulated (this.value, firstnamewhite, blackplayername, firstnameblack, isformvalid);
document.getElementById("submit-button").disabled = !isformvalid;
});
});
function disablewhenmandatorynamemissingwhitename(whiteplayername, blackplayername, firstnameblack, firstnamewhite, lastnameblack, lastnamewhite) {
if (whiteplayername !== "") {
firstnamewhite.disabled = true;
lastnamewhite.disabled = true;
} else {
firstnamewhite.disabled = false;
lastnamewhite.disabled = false;
}
}
function disablewhenmandatorynamemissingblackname(whiteplayername, blackplayername, firstnameblack, firstnamewhite, lastnameblack, lastnamewhite) {
if (blackplayername !== "") {
firstnameblack.disabled = true;
lastnameblack.disabled = true;
} else {
firstnameblack.disabled = false;
lastnameblack.disabled = false;
}
};
function checkeitherfirstorfullnamepopulated(whiteplayername, firstnamewhite, blackplayername, firstnameblack, isformvalid) {
if ((whiteplayername === "" || whiteplayername === null) && (firstnamewhite.trim() === "")) {
return false;
}
else if ((blackplayername === "" || blackplayername === null) && (firstnameblack.trim() === "")) {
return false;
}
return true;
};
</script>
<body style="background-color:rgb(68, 57, 57);">
<div class="warning">
<p id="warningtext"></p><br>
</div>
<div class="topnav">
<a th:href="#{main.html}"><i class="material-icons"
style="border:2px;font-size:60px;color:rgb(0, 0, 0);">arrow_back</i></a>
</div>
<div class="formformat">
<form th:object="${game}" th:action="#{/addgame}" th:method="post">
<label for="whiteplayername">Select white player:</label>
<select name="whiteplayername" id="whiteplayername" th:object="${names}" th:field="${game.whitePlayerName}">
<option th:value="null" th:selected="${game.name == null}"></option>
<th:block th:each="name : ${names}">
<option th:value="${name.name}"
th:text="${name.name}"></option>
</th:block>
</select>
<label for="blackplayername">Select black player:</label>
<select name="blackplayername" id="blackplayername" th:object="${names}" th:field="${game.blackPlayerName}">
<option th:value="null" th:selected="${game.name == null}"></option>
<th:block th:each="name : ${names}">
<option th:value="${name.name}"
th:text="${name.name}"></option>
</th:block>
</select><br><br>
<label for="firstnamewhite">First name white:</label>
<input type="text" id="firstnamewhite" th:field="*{firstNameWhite}"/>
<label for="firstnameblack">First name black:</label>
<input type="text" id="firstnameblack" th:field="*{firstNameBlack}"/><br><br>
<label for="lastnamewhite">Last name white:</label>
<input type="text" id="lastnamewhite" th:field="*{lastNameWhite}"/>
<label for="lastnameblack">Last name black:</label>
<input type="text" id="lastnameblack" th:field="*{lastNameBlack}"/><br><br>
<label for="date">Date:</label><br>
<input type="date" id="date" th:field="*{date}">
<table>
<tr>
<th>Move</th>
<th>White</th>
<th>Black</th>
</tr>
<tr>
<td>1</td>
<td><input type="text" id="white1" th:field="*{moves}"></td>
<td><input type="text" id="black1" th:field="*{moves}"></td>
</tr>
</table>
<input type="submit" value="Submit" id="submit-button">
</form>
</div>
<br><br>
</body>
</html>
Here's a solution that should meet all your requirements:
<script type="module">
const form = document.getElementById("form");
const submitButton = document.getElementById("submitbutton");
const whitePlayerName = document.getElementById("whiteplayername");
const blackPlayerName = document.getElementById("blackplayername");
const firstNameBlack = document.getElementById("firstnameblack");
const firstNameWhite = document.getElementById("firstnamewhite");
const lastNameWhite = document.getElementById("lastnamewhite");
const lastNameBlack = document.getElementById("lastnameblack");
form.addEventListener('change', () => {
const whiteNameSelected = whitePlayerName.value;
// Disable white name inputs if white name is selected in the dropdown
firstNameWhite.disabled = whiteNameSelected;
lastNameWhite.disabled = whiteNameSelected;
// Determine if the white name is either selected or typed in the inputs
const validWhiteName = whiteNameSelected || (firstNameWhite.value && lastNameWhite.value);
const blackNameSelected = blackPlayerName.value;
// Disable black name inputs if black name is selected in the dropdown
firstNameBlack.disabled = blackNameSelected;
lastNameBlack.disabled = blackNameSelected;
// Determine if the black name is either selected or typed in the inputs
const validBlackName = blackNameSelected || (firstNameBlack.value && lastNameBlack.value);
const submitAvailable = validWhiteName && validBlackName;
submitButton.disabled = !submitAvailable;
});
</script>
<form th:object="${game}" th:action="#{/addgame}" th:method="post" id="form">
<label for="whiteplayername">Select white player:</label>
<select name="whiteplayername" id="whiteplayername" th:object="${names}" th:field="${game.whitePlayerName}">
<option th:value="null" th:selected="${game.name == null}"></option>
<option value="name1">Name 1</option>
<option value="name2">Name 2</option>
</select>
<label for="blackplayername">Select black player:</label>
<select name="blackplayername" id="blackplayername" th:object="${names}" th:field="${game.blackPlayerName}">
<option th:value="null" th:selected="${game.name == null}"></option>
<option value="name1">Name 1</option>
<option value="name2">Name 2</option>
</select><br><br>
<label for="firstnamewhite">First name white:</label>
<input type="text" id="firstnamewhite" th:field="*{firstNameWhite}"/>
<label for="firstnameblack">First name black:</label>
<input type="text" id="firstnameblack" th:field="*{firstNameBlack}"/><br><br>
<label for="lastnamewhite">Last name white:</label>
<input type="text" id="lastnamewhite" th:field="*{lastNameWhite}"/>
<label for="lastnameblack">Last name black:</label>
<input type="text" id="lastnameblack" th:field="*{lastNameBlack}"/><br><br>
<label for="date">Date:</label><br>
<input type="date" id="date" th:field="*{date}">
<button id="submitbutton" disabled>Submit</button>
</form>
It works by combining all the logic into a single handler for the entire form change. Then, if a name is selected in the dropdown, it disables the custom name fields, if not, it leaves them enabled. The code checks to make sure both white and black name are valid and depending on that sets the submit button enabled/disabled state.
You didn't post your whole HTML so I added the button by hand and also your selects are populated dynamically so I had to hardcode some options in them. Please, for Stack Overflow questions, always post examples reproducible by other people to aid them in helping you.
Can you provide the html code too? I also recommend to name properly ur variables and fucntions beacuase are pretty illegibles by the way. Try to type the first letter of each word that compunds the varibale in uppercase at least.
Instead of:
let firstnameblack
Do:
let firstNameBlack
I also recommend to put 2 or 3 letters according to what specifies this varibale, for example if it's a button, do:
let btnFirstNameBlack
Anyways if you can provide the html code maybe I can help you with the button issue.
The instructions goes as follows:
Ask the user to enter a quantity in inches (in a textbox).
Have a select box with options for: Feet, Centimeters, Yards.
If they chose inches, calculate the conversion as 1 inch = 0.0833 feet. For Centimeters: 1 inch = 2.54 centimeters. For Yards, 1 inch = 0.02778.
Because the user may enter a decimal amoung (e.g. 3.99), be sure to parse using the parseFloat option.
Using a reference: Look up the toFixed() function and make sure that your result is outputted to 2 decimal places.
Output to a div section called results. Output using the innerHTML command.
This is the code that I currently have in place
function convertCurrency(r) {
document.getElementById("cnvrtMoney").innerHTML = "output";
if (dropdown == "feetConversion".parseFloat(r)) {
Convert = Convert / 0.0833;
} else if (dropdown == "centimetersConversion".parseFloat(r)) {
Convert = Convert / 2.54;
} else if (dropdown == "yardsConversion".parseFloat(r)) {
Convert = Convert / 0.02778;
}
Convert = Convert.toFixed(2);
var resultsString = "The amount would be" + Convert;
document.getElementById('results').innerHTML = resultsString;
}
body {
background-color: gray;
}
#heading {
background-color: lightgray;
text-align: center;
}
#formConverter {
background-color: white;
text-align: center;
text-justify: auto;
}
#EndResults {
background-color: darkgray;
text-align: center;
}
<html>
<head>
<meta charset="utf-8">
<title>Assignment 01: Currency Converter</title>
</head>
<body>
<div id="heading">
<h1> Currency Converter </h1>
<img src="CurrencyConverter.jpg" alt="Currency Converter Banner" width="600" height="200">
</div>
<div id="formConverter">
<form action="CurrencyConverter.php" method="get">
Enter Quantity (In Inches): <input type="text" name="inputInches" /><br> Select Conversion:
<select name="dropdown">
<option value="feetConversion">Feet </option>
<option value="centimetersConversion">Centimeters </option>
<option value="yardsConversion">Yards </option>
</select>
</form>
</div>
<div id="results">
</div>
</body>
</html>
I'm trying to make it display once the user clicks on the dropdown button with the exact conversion that it needs to be. If anyone could help I would greatly appreciate it.
First, this is JavaScript code, you do not need <form>.
Second, to access elements by ID you have to set ID attribute instead of NAME.
Third, math is wrong.
Forth...
It's better to show working code. This is event handler:
function convertCurrency() {
var dropdown = document.getElementById("dropdown").value;
var inputInches = document.getElementById("inputInches").value;
switch (dropdown){
case "feetConversion":
Convert = inputInches * 0.0833;
break;
case "centimetersConversion":
Convert = inputInches * 2.54;
break;
case "yardsConversion":
Convert = inputInches * 0.02778;
break;
}
var resultsString = "The amount would be: " + Convert;
document.getElementById("results").innerHTML = resultsString;
}
This is HTML layout:
<input type="text" id="inputInches"/><br>
Select Conversion:
<select id="dropdown" onchange="convertCurrency()">
<option value="" disabled="disabled" selected="selected"></option>
<option value="feetConversion">Feet </option>
<option value="centimetersConversion">Centimeters </option>
<option value="yardsConversion">Yards </option>
</select>
<div id="results"></div>
http://jsfiddle.net/ArtyomShegeda/xbj5pf62/13/
You never call convertCurrency. You need an event listener that calls it. You could put a "Convert" button in the form, and call it when they click on the button.
Code like if (dropdown == "feetConversion".parseFloat(r)) makes no sense. parseFloat() is a global function, it's not a method of a string. You just want to compare dropdown to the string. parseFloat should be used to set the Convert variable at the beginning of the function.
You don't need an action or method in a form that's being processed in JavaScript, not the server.
You never set the value of dropdown. You need to get that from the value of the dropdown. I added an ID to it, and get that using document.getElementById("selectConversion").value
There's no element cnvrtMoney. I'm not sure what the point of document.getElementById("cnvrtMoney").innerHTML = "output"; is supposed to be. I've removed it.
Your conversions are all wrong, you're dividing when you should be multiplying.
function convertCurrency(r) {
var dropdown = document.getElementById("selectConversion").value;
var Convert = parseFloat(r);
if (dropdown == "feetConversion") {
Convert = Convert / 12;
} else if (dropdown == "centimetersConversion") {
Convert = Convert * 2.54;
} else if (dropdown == "yardsConversion") {
Convert = Convert / 36;
}
Convert = Convert.toFixed(2);
var resultsString = "The amount would be " + Convert;
document.getElementById('results').innerHTML = resultsString;
}
document.getElementById("convertButton").addEventListener("click", function() {
convertCurrency(document.getElementById("inputInches").value);
});
body {
background-color: gray;
}
#heading {
background-color: lightgray;
text-align: center;
}
#formConverter {
background-color: white;
text-align: center;
text-justify: auto;
}
#EndResults {
background-color: darkgray;
text-align: center;
}
<html>
<head>
<meta charset="utf-8">
<title>Assignment 01: Currency Converter</title>
</head>
<body>
<div id="heading">
<h1> Currency Converter </h1>
<img src="CurrencyConverter.jpg" alt="Currency Converter Banner" width="600" height="200">
</div>
<div id="formConverter">
<form>
Enter Quantity (In Inches): <input type="text" name="inputInches" id="inputInches" /><br> Select Conversion:
<select name="dropdown" id="selectConversion">
<option value="feetConversion">Feet </option>
<option value="centimetersConversion">Centimeters </option>
<option value="yardsConversion">Yards </option>
</select>
<br>
<input type="button" value="Convert" id="convertButton">
</form>
</div>
<div id="results">
</div>
</body>
</html>
Ok, I had to rewrite the entire thing, but here it is
function convertCurrency(r) {
let c = document.getElementById('q').value;
let v = document.getElementById('c').value;
switch(v){
case "feet":
result = c / 0.0833;
break;
case "cent":
result = c / 2.54;
break;
case "yard":
result = c /0.02778;
break;
}
result = result.toFixed(2);
var resultsString = "The amount would be " + result;
document.getElementById('results').innerHTML = resultsString;
}
body {
background-color: gray;
}
#heading {
background-color: lightgray;
text-align: center;
}
#formConverter{
background-color: white;
text-align: center;
text-justify:auto;
}
#results{
background-color:darkgray;
text-align: center;
}
<div id="heading">
<h1> Currency Converter </h1>
<img src="CurrencyConverter.jpg" alt="Currency Converter Banner" width="600" height="200">
</div>
<div id="formConverter">
<p>
Enter Quantity (in inches):
<input type="number" id="q" name="q">
</p>
<p>
Select conversion:
<select id="c" name="c">
<option value="feet">Feet</option>
<option value="cent">Centimeters</option>
<option value="yard">Yards</option>
</select>
</p>
<button onclick="convertCurrency()">
Convert
</button>
</div>
<div id="results">
</div>
There's a lot needing to be fixed here, but changing the contents of your script tag to the following should work:
<script>
window.onload = function() {
var form = document.getElementById( "convert-input" );
form.getElementsByTagName( "select" )[ 0 ].addEventListener( "input", function(){
convertCurrency( this.value, form.getElementsByTagName( "input" )[ 0 ].value );
}, true );
}
function convertCurrency( dropdown, r) {
if (dropdown == "feetConversion"){
Convert = parseFloat(r) * 0.0833;
}
else if (dropdown == "centimetersConversion"){
Convert = parseFloat(r) * 2.54;
}
else if (dropdown == "yardsConversion"){
Convert = parseFloat(r) * 0.02778;
}
Convert = Convert.toFixed(2);
var resultsString = "The amount would be " + Convert;
document.getElementById('results').innerHTML = resultsString;
}
</script>
Note that your conversions were incorrect as you had chosen a scaling factor that needed multiplication
I have to make a div triangle like this, with looping in JavaScript. Anyone know how to make this?
*Input using <select> tag. Thanks!
Check this
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script>
$(document).ready(function () {
var container = $("#html2");
$("#CreateDiv").change(function () {
$('#html2').html('');
var strBlocksHTML = '';
var selectedvalue = $("#CreateDiv option:selected").val();
for (var i = 0; i <= selectedvalue; i++) {
for (var n = 0; n < i ; n++) {
strBlocksHTML += '<div id="pdfDiv" style=" background-color:red; display:inline-block; width:50px; height:50px; margin:2px 5px; border:2px solid #ccc;"> </div>';
}
strBlocksHTML += '<div></div>';
}
$('#html2').append(strBlocksHTML);
})
});
</script>
</head>
<body style="text-align:center">
<div>
<select id="CreateDiv">
<option value="0"> Select</option>
<option value="1"> One</option>
<option value="2"> Two</option>
<option value="3"> There</option>
<option value="4"> Four</option>
<option value="5"> Five</option>
</select>
</div>
<br />
<br />
<div id="html2" style="text-align:center">
</div>
</body>
</html>
Simple double loop. First loop for rows, second for single div.
var levels = 5;
var output = '';
for (var row = 1; row <= levels; row++) {
output += '<div class="row">';
for (var i = 0; i < row; i++) {
output += '<div class="item"></div>'
}
output += '</div>';
}
document.write(output);
.row {
text-align: center;
}
.item {
display: inline-block;
width: 40px;
height: 40px;
border: 1px solid green;
background: gray;
}
I am having some issues creating a game using javascript. I cant use jquery. The problem I am having is when I select the blurred image it doesnt unblur and it should do. I have tried changing the names of the functions, the images, the onload names but that doesnt seem to have worked. I have also checked the F12 developer tools and made the changes it needed, still no luck making it work.
Can someone please have a look at the code below and give me some help as to why it isnt working. I am new to javascript so im still getting used to it.
<!DOCTYPE html>
<html>
<head>
<title> Who Am I? </title>
<script type="text/javascript">
var imageone = document.getElementById("Zero");
var imagetwo = document.getElementById("One");
var imagethree = document.getElementById("Two");
var imagefour = document.getElementById("Three");
var imagefive = document.getElementById("Four");
var imagesix = document.getElementById("Five");
window.onload = init1;
function init1 () {
var imageone = document.getElementById("Zero");
imageone.onclick = showAnswerone;
}
function showAnswerone () {
var imageone = document.getElementById("Zero");
imageone.src="Zero.jpg";
}
window.onload = init2;
function init2 () {
var imagetwo = document.getElementById("One");
imagetwo.onclick = showAnswertwo;
}
function showAnswertwo () {
var imagetwo = document.getElementById("One");
imagetwo.src="One.jpg";
}
window.onload = init3;
function init3 () {
var imagethree = document.getElementById("Two");
imagethree.onclick = showAnswerthree;
}
function showAnswerthree () {
var imagethree = document.getElementById("Two");
imagethree.src="Two.jpg";
}
window.onload = init4;
function init4 () {
var imagefour = document.getElementById("Three");
imagefour.onclick = showAnswerfour;
}
function showAnswerfour () {
var imagefour = document.getElementById("Three");
imagefour.src="Three.jpg";
}
window.onload = init5;
function init5 () {
var imagefive = document.getElementById("Four");
image.onclick = showAnswerfive;
}
function showAnswerfive () {
var imagefive = document.getElementById("Four");
imagefive.src="Four.jpg";
}
window.onload = init6;
function init6 () {
var imagesix = document.getElementById("Five");
imagesix.onClick = showAnswersix;
}
function showAnswersix () {
var imagesix = document.getElementById("Five");
imagesix.src="Five.jpg";
}
function submitForm()
{
var var_one = 0, var_two = 0, var_three = 0;
var var_four = 0, var_five = 0, var_six = 0;
}
function var_oneb(){
var_one=5;
return true;
}
function var_onea(){
var_one=0;
return true;
}
function var_twob(){
var_two=5;
return true;
}
function var_twoa(){
var_two=0;
return true;
}
function var_threeb(){
var_three=5;
return true;
}
function var_threea(){
var_three=0;
return true;
}
function var_fourb(){
var_four=5;
return true;
}
function var_foura(){
var_four=0;
return true;
}
function var_fiveb(){
var_five=5;
return true;
}
function var_fivea(){
var_five=0;
return true;
}
function var_sixb(){
var_six=5;
return true;
}
function var_sixa(){
var_six=0;
return true;
}
function results_addition() {
var var_results=var_one+var_two+var_three+var_four+var_five+var_six;
if(var_results<=29){
document.getElementById('choice1').value="Not all answers are correct";
}
else{
if(var_results>=30){
document.getElementById('choice1').value="All answers are correct";
}
else{
document.getElementById('choice1').value="All answers are correct";
}
}
}
</script>
<style>
body {
background-color: #ff0000;
}
div#grid {
position: relative;
width: 500px;
height: 300px;
margin-left: 50;
margin-right: 50;
}
table {
border-spacing: 0px;
position: absolute;
left: 40px;
top: 40px;
border-collapse: collapse;
padding: 0px;
margin: 0px;
}
td {
border: 1px solid white;
text-align: center;
width: 160px;
height: 110px;
vertical-align: middle;
align-content: stretch;
padding: 5px;
margin: 0px;
}
h2 {
font-family: verdana, arial;
text-align: center;
color: white;
font-size: 30px;
}
h3 {
font-family: verdana, arial;
text-align: center;
color: white;
font-size: 18px;
}
</style>
</head>
<body>
<div id="grid">
<h2> Who Am I? </h2>
<table>
<tr>
<td> <img id = "Zero" src = "Zeroblur.jpg"> </td>
<td> <img id = "One" src = "Oneblur.jpg"> </td>
<td> <img id = "Two" src = "Twoblur.jpg"> </td>
</tr>
<tr>
<td> <img id = "Three" src = "Threeblur.jpg"> </td>
<td> <img id = "Four" src = "Fourblur.jpg"> </td>
<td> <img id = "Five" src = "Fiveblur.jpg"> </td>
</tr>
</table>
</div>
<br><br><br><br><br><br><br><br>
<h3> I am a Rugby League Player. </h3>
<h3> Click on me to reveal my identity! </h3>
<br>
<h3>Which Player am I</h3>
<hr>
<form action="">
<h3>Player 1 </h3>
<center>
<h3>
Shaun Johnson <INPUT TYPE="radio" NAME="Ra1" VALUE="0" OnClick="var_onea()">
Sonny Bill Williams <INPUT TYPE="radio" NAME="Ra1" VALUE="5" OnClick="var_oneb()">
</h3>
</center>
<br>
<hr>
<h3>Player 2 </h3>
<center>
<h3>
Gareth Widdop <INPUT TYPE="radio" NAME="Ra2" VALUE="0" OnClick="var_twoa()">
Sam Tomkins <INPUT TYPE="radio" NAME="Ra2" VALUE="5" OnClick="var_twob()">
</h3>
</center>
<br>
<hr>
<h3>Player 3 </h3>
<center>
<h3>
James Graham <INPUT TYPE="radio" NAME="Ra3" VALUE="5" OnClick="var_threea()">
Sam Burgess <INPUT TYPE="radio" NAME="Ra3" VALUE="10" OnClick="var_threeb()">
</h3>
</center>
<br>
<hr>
<h3>Player 4 </h3>
<center>
<h3>
Matthew Scott <INPUT TYPE="radio" NAME="Ra4" VALUE="5" OnClick="var_foura()">
Johnathon Thurston <INPUT TYPE="radio" NAME="Ra4" VALUE="10" OnClick="var_fourb()">
</h3>
</center>
<br>
<hr>
<h3>Player 5 </h3>
<center>
<h3>
Neil Lowe <INPUT TYPE="radio" NAME="Ra5" VALUE="5" OnClick="var_fivea()">
Danny Brough <INPUT TYPE="radio" NAME="Ra5" VALUE="10" OnClick="var_fiveb()">
</h3>
</center>
<br>
<hr>
<h3>Player 6 </h3>
<center>
<h3>
Mitch Garbutt <INPUT TYPE="radio" NAME="Ra6" VALUE="5" OnClick="var_sixa()">
Ryan Hall <INPUT TYPE="radio" NAME="Ra6" VALUE="10" OnClick="var_sixb()">
</h3>
</center>
<br>
<hr>
<br>
<center>
<INPUT TYPE="button" VALUE="Calculate" OnClick="results_addition()"> Your Score:
<INPUT TYPE="text" id="choice1" NAME="choice1" VALUE="" SIZE=20>
</center>
</form>
</body>
</html>
Short answer that should get you back on track:
You're using onClick instead of onclick to add your click event listener to the images.
Longer answer that might help to get everything to work correctly:
The way you're attaching event listeners to DOM Events (such as a "click" or a "load") can be improved. Currently, you're overwriting the onload method 5 times:
window.onload = init1;
// ...
window.onload = init2;
// ...
// etc.
By the time the window is loaded, only the last set init method will execute (init6, in your case).
If you want to use window.onload = method;, you'll have to create one init method that executes all separate init methods. Like so:
function init() {
init1();
init2();
// etc.
};
window.onload = init;
Event better is to add event listeners via the addEventListener method. By using addEventListener, you can add multiple methods that will be executed when an event happens. You can read more about this method on this MDN page.
// For just one event listener, this can work:
element.onclick = onClick;
// If you want to execute multiple methods when an event happens, you'll need:
element.addEventListener("click", doSomething);
element.addEventListener("click", doSomethingElse);
Other than your event handling, there's quite some other stuff you can improve. There's a lot of duplicate code and functions that sort of do the same things but have different names. But I guess that's a different question/topic.
I have been working on this form and can't get past the CalculateTotal. I am completely lost on how to get this to add up and display in the box. Can anyone help?
Here is my jsfiddle http://jsfiddle.net/clbacon70/x6kjqbop/1/
var gc_fSandwichPrice = 5.99; // Price for each sandwich
var gc_fExtrasPrice = 1.50; // Price for each extra item
// GLOBAL VARS
// Global object vars
var divErrors;
var radSandwich;
var radSize;
var chkExtras;
// Other global vars
var g_fTotal;
var g_sSandwich;
var g_sSize;
var g_sExtras;
window.addEventListener('load', Init);
function Init() {
document.getElementById("h1Title").innerHTML = "Dirty Deli 1.0";
var spanExtrasPrice = document.getElementById("spanExtrasPrice");
var btnCalculateTotal = document.getElementById("btnCalculateTotal");
divErrors = document.getElementById("divErrors");
radSandwich = document.getElementsByName('radSandwich');
radSize = document.getElementsByName('radSize');
chkExtras = document.getElementsByName('chkExtras');
spanExtrasPrice.innerHTML = gc_fExtrasPrice.toFixed(2);
btnCalculateTotal.addEventListener('click', CalculateTotal);
} // function Init()
function CalculateTotal() {
divErrors.innerHTML = '';
if (radSandwich[0].checked) {
g_sSandwich = radSandwich[0].value;
} else if (radSandwich[1].checked) {
g_sSandwich = radSandwich[1].value;
} else if (radSandwich[2].checked) {
g_sSandwich = radSandwich[2].value;
} else if (radSandwich[3].checked) {
g_sSandwich = radSandwich[3].value;
} else {
divErrors.innerHTML = "Select a Sandwich";
return;
}
if (radSize[0].checked){
g_fTotal = radSize[0].title;
} else if (radSize[1].checked) {
g_fTotal = radSize[1].title;
} else if (radSize[2].checked) {
g_fTotal = radSize[2].title;
} else {
divErrors.innerHTML = "Please choose a size";
return;
}
if (chkExtras[0].checked) {
g_sExtras = chkExtras[0].value;
g_fTotal = g_fTotal + gc_fExtrasPrice;
}
if (chkExtras[1].checked) {
g_sExtras = g_sExtras + ',' + chkExtras[1].value;
g_fTotal = g_fTotal + gc_fExtrasPrice; }
if (chkExtras[2].checked) {
g_sExtras = g_sExtras +', ' + chkExtras[2].value;
g_fTotal = g_fTotal + gc_fExtrasPrice;
}
var textTotal = document.getElementById('textTotal');
textTotal.value = g_fTotal;
} // function CalculateTotal
function ProcessOrder() {
} // function ProcessOrder
* {
margin: 0;
padding: 0;
}
body {
background-color: #333;
}
#divWrapper {
background-color: #efe;
width: 40em;
border: solid black;
border-radius: 0 0 20px 20px;
border-width: 0 1px 1px 1px;
margin: 0 auto;
padding: 2em 1em;
}
h2 {
font-style: italic;
font-size: 1.3em;
color: #666;
margin-top: 0px;
}
input {
margin-right: 0.3em;
}
h3, p {
margin: 0.5em 0;
}
div#divErrors {
font-size: 110%;
color: white;
background: #f00;
margin-bottom: 0.5em;
}
#divPaymentInfo {
margin: 10px 0 20px 0;
padding-bottom: 10px;
border: solid black;
border-width: 1px 0;
}
#divCreditCardInfo {
font-size: .8em;
visibility: hidden;
margin-left: 1em;
display: inline;
}
#divOrder {
background: white;
min-height: 10em;
width: 25em;
border: 1px solid black;
margin: 0.5em 0;
padding: 10px;
}
<body>
<div id="divWrapper">
<form name="frmMain">
<h1 id="h1Title">Deli Form</h1>
<h2>Part 1</h2>
<h3>Sandwich</h3>
<label><input type="radio" name="radSandwich" value="Breast of Chicken">Breast of Chicken</label><br>
<label><input type="radio" name="radSandwich" value="Leg of Lamb">Leg of Lamb</label><br>
<label><input type="radio" name="radSandwich" value="Loin of Ham">Loin of Ham</label><br>
<label><input type="radio" name="radSandwich" value="ReelMeat®">ReelMeat®</label><br>
<br>
<h3>Size</h3>
<label><input type="radio" name="radSize" value="Manly Man" title="$4.99">Manly Man</label>
<label><input type="radio" name="radSize" value="Girly Man" title="$5.99">Girly Man</label>
<label><input type="radio" name="radSize" value="Super Girly Man" title="$6.99">Super Girly Man</label>
<br><br>
<h3>Extras ($<span id="spanExtrasPrice"></span> each)</h3>
<label><input type="checkbox" name="chkExtras" value="Deep-Fried Spam">Deep-Fried Spam</label><br>
<label><input type="checkbox" name="chkExtras" value="Toenails">Toenails</label><br>
<label><input type="checkbox" name="chkExtras" value="Secret Sauce">Secret Sauce</label><br>
<br><br>
Total: <input type="text" id="txtTotal" size="5"> <input type="button" id="btnCalculateTotal" value="Calculate Total">
<br><br>
<div id="divErrors"></div>
<div id="divPaymentInfo">
<h2>Part 2</h2>
<strong>Customer's Name:</strong> <input type="text" id="txtName">
<br><br>
<strong>Payment:</strong>
<select id="selPayment">
<option value="Cash" selected="selected">Cash</option>
<option value="Check">Check</option>
<option value="Credit Card">Credit Card</option>
</select>
<div id="divCreditCardInfo">
Card Number: <input type="text" id="txtCreditCardNbr" size="20">
Month: <input type="text" id="txtMonth" size="2"> Year:
<select id="selYear">
<option value="" selected="selected"></option>
<option 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="2010">2017</option>
<option value="2011">2018</option>
</select>
</div><!-- divCreditCardInfo -->
</div><!-- divPaymentInfo -->
<input type="button" id="btnProcessOrder" value="Process Order">
<div id="divOrder"></div>
<input type="reset" value="Reset">
</form>
</div> <!-- divWrapper -->
</body>
You have a typo in your javascript. You are attempting to fetch an html element with id textTotal, when the field you're interesting in is actually given the id txtTotal.
Fix that typo and it will work.
var textTotal = document.getElementById('textTotal');
Your selector is wrong. The element id of your textbox is txtTotal
so the following should work:
var textTotal = document.getElementById('txtTotal');
Here's a fixed copy of your jsFiddle: http://jsfiddle.net/dcseekcw/
What I fixed:
You were passing in $ along with values you were trying to add as floats. Removed them from your title values and only put it back in after the total is calculated.
Put in parseFloat so values could be added together instead of being concatenated as strings.
Initialised your g_fTotal and chkExtras variables.
Put in some basic checking so that radSize doesn't cause problems when it's not selected.
You have to add brackets after 'Init'.
window.addEventListener('load', Init());
And also there was a typo in the end of CalculateTotal function.
Here is working example:
http://jsfiddle.net/x6kjqbop/3/