I was trying to make a content score as a class assignment.
Assume : (The user sees a URL and then select the checkboxes that are assigned to issues . Each issue is assigned a score in a array.)
Whats working :
Individual checks are registered with their respective scores being displayed
Whats not working :
Can someone help me to update the score ( as the user checks the checkbox or unchecks).
I am assuming in future if i want to increase the issues I will be able to do that since it is in an array. (am i right)
(my week 4 in JS)
//Set up an array with the respective score
var code = new Array();
code["v1"] = 1;
code["v2"] = 2;
code["v3"] = 3;
code["v4"] = 5;
// As the user selects the checkbox I want to keep on adding the score and as the user unchecks I want to recalculate and display.
function getvalueScore() {
var score = 0;
//Get a reference to the form
var theForm = document.forms["contentForm"];
//Get a reference to the score from the "ContentForm"
var contentScore = theForm.elements["contentScore"];
// loop through each check box
for (var i = 0; i < contentScore.length; i++) {
//if the radio button is checked
if (contentScore[i].checked) {
// I want to calculate and keep updating the score
score = code[contentScore[i].value];
}
}
//return score
return score;
}
function calculateTotal() {
//calculation for final score
var scoreCard = getvalueScore();
//display the result
var divobj = document.getElementById('totalPrice');
divobj.style.display = 'block';
divobj.innerHTML = "Your Content Score is " + scoreCard;
}
function hideTotal() {
var divobj = document.getElementById('totalPrice');
divobj.style.display = 'none';
}
<!DOCTYPE html>
<html>
<head>
<title>Content Score</title>
<meta charset="utf-8">
<script src="formcalculations.js"></script>
</head>
<body onload='hideTotal()'>
<div id="wrap">
<form action="" id="contentForm" onsubmit="return false;">
<div>
<div class="cont_order">
Content Score</br>
<label>Please select the issues you see on the page to calculate the content score</label>
</br>
<label class='radiolabel'>
<input type="checkbox" name="contentScore" value="v1" onclick="calculateTotal()" />No content value</label>
<br/>
<label class='radiolabel'>
<input type="checkbox" name="contentScore" value="v2" onclick="calculateTotal()" />Mediocre content value</label>
<br/>
<label class='radiolabel'>
<input type="checkbox" name="contentScore" value="v3" onclick="calculateTotal()" />Obsolete content</label>
<br/>
<label class='radiolabel'>
<input type="checkbox" name="contentScore" value="v4" onclick="calculateTotal()" />Irrelevant content</label>
<br/>
<br/>
<br/>
<div id="totalPrice"></div>
</div>
</div>
</form>
</div>
<!--End of wrap-->
</body>
</html>
In your code you assign last selected checkbox to score variable, so the only thing you need to do is to sum the scores with:
score += code[contentScore[i].value];
Related
I am new to javaScript.
HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Example</title>
<style>
body { "background-color: #fff; color: #000; font-size: 14px;
position: relative;}
form {
font-size:16px;
}
</style>
</head>
<!-- Embedded css style -->
<body>
<div>
<header>
<h1>Example</h1>
</header>
<div class= "container">
<main>
<form>
<fieldset>
<legend>
Example
</legend>
<!--asks for name-->
<label for="nameInput">Name</label>
<input type="text" id="nameInput" name="name" placeholder="John Doe" />
<br>
<!--asks for purchase price -->
<label for="amt">Amount:</label>
<input type="text" id="amt"><br>
<!--asks for state-->
<input type="radio" name="stateCode" value="k" id="k" checked> Kansas
<input type="radio" name="stateCode" value="c" id="c"> California
<input type="radio" name="stateCode" value="m" id="m">Missouri
<br>
<label for="tax">Tax :</label>
<input type="text" id="tax" disabled><br>
<label for="totalCost">Your total is:</label>
<input type="text" id="totalCost" disabled><br>
<label> </label>
<input type="button" id="calculate" value="Calculate"><br>
</fieldset>
</form>
</main>
</div><!-- end .container -->
</div><!--end of #pushDown -->
</body>
</html>
javascript:
// returns a html element (id)
var $ = function(id) {
return document.getElementById(id);
};
// calculates total after sales tax
function coffeeCalc(amt,tax) {
var totalCost = amt + tax;
totalCost = totalCost.toFixed(2); // 2 decimals
return totalCost; // returns value
}
function init() {
// assign variables to id and class values from HTML page
var amt = parseFloat( $("amt").value);
// declaring variables
var taxRate;
var stateSelected; // for console log purpose only
// radio buttons
if ($("k").checked) {
taxRate = .087; // tax rate: 8.7%
stateSelected = "Kansas";
} else if ($("c").checked) {
taxRate = .077; // tax rate: 7.7%
stateSelected = "California";
} else {
taxRate = .09; // tax rate: 9%
stateSelected = "Missouri";
}
var tax = amt * taxRate;
// shows output
$("tax").value = tax.toFixed(2); // 2 decimals
$("totalCost").value = coffeeCalc(amt,tax); //calls the coffeeCalc function
}
Image 1:
On the bottom right side: it shows totalCost: input#totalCost. The debugger displays amt: 10, so therefore I would think it would resemble amt except it should be:
total: 10.87.
Image 2: After I finish debugging the last line:
console.log(“Total Cost: “ + $(“totalCost).value);
it opens a new tab: VM236 with amt
What does that mean?
The variable totalCost in your screenshot refers to the DOM element, not the value from the coffeeCalc function, since that has already completed by the time your breakpoint has been reached (and the totalCost variable is locally scoped to that function).
You can see by typing totalCost into the console (without having broken) that there is a globally-scoped variable called totalCost, the value of which is the input element. (See screenshot here)
Regarding the new tab, the debugger is simply continuing to step through code that's running. VM... files are generated by Chrome's Dev Tools for scripts that have no sourceURL (that have been injected dynamically).
You say you are new to JS, so if you haven't already, you might want to take a look Chrome's official 'Getting Started' guide to debugging.
I recently changed my code to make it more responsive and as such messed up my jQuery code to record correct vs incorrect answers to a small quiz. The javascript that I posted below used to work just fine when the question was located in an HTML form tag. How can I modify the jQuery code in the second line (where the 'answer1' variable is declared) to work properly now that a form tag no longer surrounds my question? Thanks very much.
HTML
<div class="intro-header2">
<div class="container">
<h1>The capital of Croatia is ...</h1>
<p> </p>
<div class="radio" style="margin-top: 0px;">
<label><input type="radio" name="capital" value="zagreb" id="zagrebID"> Zagreb</label>
</div>
<div class="radio" style="margin-top: 10px;">
<label><input type="radio" name="capital" value="debrovnik"> Debrovnik</label>
</div>
<div class="radio" style="margin-top: 10px;">
<label><input type="radio" name="capital" value="makarska"> Makarska</label>
</div>
<div class="radio" style="margin-top: 10px;">
<label><input type="radio" name="capital" value="moscow"> Moscow</label>
</div>
<div class="radio" style="margin-top: 20px;">
<input type="button" class="btn btn-info" value=" Next " id="NextID">
</div>
</div> <!--/.container-->
</div> <!--/.intro-header2-->
JS
$("#NextID").click(function(){
var answer1 = ($('input[name=capital]:checked', '#myForm').val());
if (answer1 == "zagreb") {
var QuestionNumber = "Question 1, The capital of Croatia.";
var QuizDesc = "Quiz questions on the country of Croatia.";
var name = localStorage.getItem('name');
var email = localStorage.getItem('email');
//pulls the current counter from local storage
var counter = localStorage.getItem('counter');
//adds one to it
var counter = parseInt(localStorage.getItem('counter')) + 1;
//updates the global variable for counter
setCounter(counter);
passedQues(email, name, QuestionNumber, QuizDesc);
document.location.replace("page3.html");
}
else if (!$("input[name='capital']:checked").val()) {
alert('Nothing is checked!');
return false;
}
else {
var QuestionNumber = "Question 1, The capital of Croatia.";
var QuizDesc = "Quiz questions on the country of Croatia.";
var name = localStorage.getItem('name');
var email = localStorage.getItem('email');
//pulls the current counter from local storage
var counter = localStorage.getItem('counter');
//adds one to it
var counter = parseInt(localStorage.getItem('counter')) + 0;
//updates the global variable for counter
setCounter(counter);
failedQues(email, name, QuestionNumber, QuizDesc);
document.location.replace("page3.html");
}
});
You no longer have the form element, and I assume that it has an id attribute with the value myForm
This line looks for the value of an input inside a an element with id myForm
var answer1 = ($('input[name=capital]:checked', '#myForm').val());
This element no longer exists, so the input value is not found. Try changing this line to:
var answer1 = ($('input[name=capital]:checked').val());
I am trying to create a javascript code for my website to do the calculations once a checkbox is checked. Each time i select a checkbox it should calculate the total price of the items.
This is my html code:
<form id="orderForm" action="#" method="get">
<section id="selectBook">
<h2>Select books</h2>
<?php
include_once('database_conn.php');
$sqlBooks = 'SELECT bookISBN, bookTitle, bookYear, catDesc, bookPrice FROM nbc_book b inner join nbc_category c on b.catID = c.catID WHERE 1 order by bookTitle';
$rsBooks = mysqli_query($conn, $sqlBooks);
while ($book = mysqli_fetch_assoc($rsBooks)) {
echo "\t<div class='item'>
<span class='bookTitle'>{$book['bookTitle']}</span>
<span class='bookYear'>{$book['bookYear']}</span>
<span class='catDesc'>{$book['catDesc']}</span>
<span class='bookPrice'>{$book['bookPrice']}</span>
<span class='chosen'><input type='checkbox' name='book[]' value='{$book['bookISBN']}' title='{$book['bookPrice']}' /></span>
</div>\n";
}
?>
</section>
<section id="collection">
<h2>Collection method</h2>
<p>Please select whether you want your chosen book(s) to be delivered to your home address (a charge applies for this) or whether you want to collect them yourself.</p>
<p>
Home address - £3.99 <input type="radio" name="deliveryType" value="home" title="3.99" checked = "checked" /> |
Collect from warehouse - no charge <input type="radio" name="deliveryType" value="trade" title="0" />
</p>
</section>
<section id="checkCost">
<h2>Total cost</h2>
Total <input type="text" name="total" id="total" size="10" readonly="readonly" />
</section>
The code has been separated into tag.
This is my current javascript code which i have written:
var item = document.getElementsByClassName("item");
var chkbox = document.getElementsByTagName("input");
for(var i = 0; i < chkbox.length; i++){
chkbox[i].onchange = function(){
//Recalculate total
getTotal();
}
}
function getTotal(){
var total = 0.0;
for(var i = 1; i <= chkbox.length; i++){
//If the checkbox is checked, add it to the total
if(chkbox[i-1].checked){
total = total + parseFloat(chkbox[i].value);
}
}
return total;
document.getElementById("total").innerHTML = total;
}
I really need some experts to help me on this. Thank you.
In getTotal() you are returning before setting the value here:
return total;
document.getElementById("total").innerHTML = total;
Set the input with the value rather than innerHTHML.
document.getElementById("total").setAttribute("value", total);
I had to change the checked to be parseFloat(chkbox[i-1].title) to match the if statement
jsFiddle
The above example uses to products, the first priced at 1 and the second at 2.
I am trying to test a java script function the purpose of the function is to get the value of a user selected form element. Specifically a radio button. my goal is to use this function in another function to calculate a price total. But for now, I just want to make sure this function returns the value of the selected radio button.
<html>
<head>
</head>
<body>
<form name="testForm">
<legend>Calculate your square feet</legend>
</br>
<label> What size plants are you starting with ? </label>
</br>
</br>
<input type="radio" name="plantType" value="16"/>Seeds, havn't started yet</label>
</br>
<input type="radio" name="plantType" value="16"/> Seedlings, less than 2ft high</label>
</br>
<input type="radio" name="plantType" value="32"/> Juvenile, 2 - 4ft high</label>
</br>
<input type="radio" name="plantType" value="64"/> Adult, 4ft or higher</label>
</br>
</form>
<script type="text/javascript">
var plant_name = new Array();
plant_name[16] = 16;
plant_name[16] = 16;
plant_name[32] = 32;
plant_name[32] = 64;
function getPlantSize() {
var plantSize = 0;
var theForm = document.testForm;
var selectedPlant = theForm.plantType;
for (var i = 0; i < plantType.length; i++)
{
if (plantType[i].checked)
{
plantSize = plant_name.[selectedPlant[i].value];
break;
}
document.write (plantSize);
}
}
</script>
</body>
</html>
-----EDITED-----
The story is not being presented properly, again, due to code error. Need fresh eyes!
function story()
{
//collect the users input data
var transport = "";
var name = document.getElementsByName("name")[0].value
var title = document.getElementsByName("title")[0].value
var noun = document.getElementsByName("noun")[0].value
var num1 = document.getElementsByName("num1")[0].value
var num2 = document.getElementsByName("num2")[0].value
var travelmeasure = document.getElementsByName("measureravel").value
//write new html to the page to display the story
document.write("<h1>"+title+"</h1>");
document.write("<p>Once upon a time,</p>");
document.write("<p>"+name+" was trying to make their way to "+noun+" in a "+transport+".</p>");
document.write("<p>Unfortunately "+name+" didn't realise how far away "+houn+" really was.</p>");
document.write("<p>The assumption was "+num1+" "+measuretravel+" when really is turned out to be "+num2+" "+measuretravel+".</p>");
document.write("<p>Thankfully "+name+" likes to travel.</p>");
document.write("<p>THE END</p>");
}
-----ORIGINAL-----
Before adding the "story" function and the "continue" button, this page was running smoothly. What I am trying to do is have the users input variables be applied to the story I wrote in a new HTML page.
I'm assuming its probably just code error but I can't seem to see it.
<html>
<head>
<title>a4_part4</title>
<script type="text/javascript">
//<![CDATA[
function storytime()
{
//displays alert
alert("Welcome to an Interactive Story Spot.");
}
function confirm()
{
var spaceship = document.getElementsByName("transport")[0].value;
var ducatti = document.getElementsByName("transport")[1].value;
var ferrari = document.getElementsByName("transport")[2].value;
var jet = document.getElementsByName("transport")[3].value;
var train = document.getElementsByName("transport")[4].value;
var transport = "";
var name = document.getElementsByName("name")[0].value
var title = document.getElementsByName("title")[0].value
var noun = document.getElementsByName("noun")[0].value
var num1 = document.getElementsByName("num1")[0].value
var num2 = document.getElementsByName("num2")[0].value
var miles = document.getElementsByName("measuretravel")[0].value
var kms=document.getElementsByName("measuretravel")[1].value;
var travelmeasure = document.getElementsByName("measureravel").value
//determine which mode of transportation was chosen
if (document.getElementsByName("transport")[0].checked)
{
transport = spaceship;
}
else if (document.getElementsByName("transport")[1].checked)
{
transport = ducatti;
}
else if (document.getElementsByName("transport")[2].checked)
{
transport = ferrari;
}
else if (document.getElementsByName("transport")[3].checked)
{
transport = jet;
}
else if (document.getElementsByName("transport")[4].checked)
{
transport = train;
}
//determine which measure of travel was chosen
if (document.getElementsByName("measuretravel")[0].checked)
{
miles = "+num1+" + "+num2+" * 1.60934
measuretravel = miles;
}
else if (document.getElementsByName("measuretravel")[1].checked)
{
measuretravel = kms;
}
//display alert
alert ("Hello, "+name+", your story values are "+title+", "+transport+", "+noun+", "+num1+", "+num2+", and "+measuretravel+" ");
}
function story()
{
//collect the users input data
{
var transport = "";
var name = document.getElementsByName("name")[0].value
var title = document.getElementsByName("title")[0].value
var noun = document.getElementsByName("noun")[0].value
var num1 = document.getElementsByName("num1")[0].value
var num2 = document.getElementsByName("num2")[0].value
var travelmeasure = document.getElementsByName("measureravel").value
//write new html to the page to display the story
document.write("<h1>"+title+"</h1>");
document.write("<p>Once upon a time,</p>");
document.write("<p>"+name+" was trying to make their way to "+noun+" in a "+transport+".</p>");
document.write("<p>Unfortunately "+name+" didn't realise how far away "+houn+" really was.</p>")
document.write("<p> The assumption was "+num1+" "+measuretravel+" when really is turned out to be "+num2+" "+measuretravel+".</p>")
document.write("<p> Thankfully "+name+" likes to travel.<p>")
document.write("<p>THE END</p>");
}
//]]>
</script>
</head>
<body>
<form id="storyform" action="">
<h1>Create Your Own Story</h1>
<p style="font-weight:bold;"> Your Name
<input type="text" name="name" id="name" value="Jane Doe">
</p>
<p style="font-weight:bold;"> Story Title
<input type="text" name="title" id="title" value="Enter Story Title Here">
</p>
<p style="font-weight:bold;">Choose A Mode Of TRANSPORTATION</p>
<input type="radio" name="transport" id="transport" value="spaceship" checked="checked"> Spaceship
<br>
<input type="radio" name="transport" id="transort1" value="ducati"> Ducati
<br>
<input type="radio" name="transport" id="transport2" value="ferrari"> Ferrari
<br>
<input type="radio" name="transport" id="transport3" value="jet"> Jet
<br>
<input type="radio" name="transport" id="transport4" value="train"> Train
<br>
<br>
Enter a NOUN <input type="text" name="noun" id="noun" value="Paris" onclick=""/>
<br>
Enter a NUMBER <input type="text" name="num1" id="num1" value="1" checked="checked" onclick=""/>
<br>
Enter Another NUMBER <input type="text" name="num2" id="num2" value="2" onclick=""/>
<p style="font-weight:bold;">Choose a means of MEASURING TRAVEL</p>
<input type="radio" name="measuretravel" id="measuretravel1" value="miles"> Miles
<br>
<input type="radio" name="measuretravel" id="measuretravel2" value="kms" checked="checked"> Kilometers
<br>
<br>
<br>
<p>Please confirm before you continue<p>
<input type="reset" value="Clear Form">
<input type="button" value="Story Time!" onclick="storytime();">
<input type="button" value="Confirm" onclick="confirm();">
<input type="button" value="Continue" onclick="story();">
</form>
</body>
</html>
it looks like there's a rogue curly brace in your Story function
This is what your function looks like right now
function story()
{
//collect the users input data
{
...
}
It's not even registering your function because you have a syntax error. You can either remove that second { or you can add a } to close it. I would do the former.
You're missing a closing "}". You have a "{" for your story function and another after "//collect the users input data", but only one closing "}"