Want to make it so prices actually reflect the choices - javascript

Hope everyone is having a good weekend!
If you select a Small Cheese pizza the price comes out to $5. However, if you select a Small Cheese and Peanut Butter, it still comes out to $5. I think I might need to add a loop/array. I am definitely missing something. Thanks for your help. Also, I am a total newbie to all of this so no answers that are may seem out of knowledge based off what I have written. Thanks!
var pizzaPrice = 0;
function Pizza(size,toppings,pizzaPrice) {
this.size = size;
this.toppings = toppings;
this.pizzaPrice = 0;
}
Pizza.prototype.price = function() {
if (this.size === "Small") {
this.pizzaPrice += 2;
}
else if (this.size === "Medium") {
this.pizzaPrice += 3;
}
else if (this.size === "Large") {
this.pizzaPrice += 4;
}
if (this.toppings === "Cheese") {
this.pizzaPrice += 3;
}
else if (this.toppings === "Cheese" && this.toppings === "Peanut Butter") {
this.pizzaPrice += 10;
console.log("hey");
}
else if (this.toppings === "Vegetarian") {
this.pizzaPrice += 2;
}
else if (this.toppings === "Supreme") {
this.pizzaPrice += 4;
}
else if (this.toppings === "Pepperoni") {
this.pizzaPrice += 3;
}
return this.pizzaPrice;
}
$(document).ready(function(){
$("form#pizza").submit(function(event){
event.preventDefault();
var size = $("input[type=radio][name=size]:checked").val();
var toppings = $("input[type=checkbox][name=toppings]:checked").val();
var newPizza = new Pizza(size,toppings,pizzaPrice);
newPizza.price();
$("#responses").append("<li>" + "You ordered a " + newPizza.size + " " + newPizza.toppings + " pizza. " + " Your total price is " + newPizza.pizzaPrice + "</li>");
});
});
<!DOCTYPE html>
<html>
<head>
<title>Pizza Pizza</title>
<link href="css/bootstrap.css" rel="stylesheet" type="text/css">
<link href="css/styles.css" rel="stylesheet" type="text/css">
<script src="js/jquery-3.2.0.js"></script>
<script src="js/scripts.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<div class="container">
<div class="jumbotron">
<h2>Pizza Toppings</h2>
</div>
<form id="pizza">
<div class="form-group">
<p>What size would you like your pizza:</p>
<input type="radio" name="size" value="Small">Small.<br>
<input type="radio" name="size" value="Medium">Medium.<br>
<input type="radio" name="size" value="Large">Large.<br>
</div>
<div class="form-group">
<p>Which toppings would you like</p>
<input type="checkbox" name="toppings" value="Cheese">Cheese.<br>
<input type="checkbox" name="toppings" value="Vegetarian">Vegetarian.<br>
<input type="checkbox" name="toppings" value="Supreme">Supreme.<br>
<input type="checkbox" name="toppings" value="Pepperoni">Pepperoni.<br>
<input type="checkbox" name="toppings" value="Fruit">Fruit.<br>
<input type="checkbox" name="toppings" value="Bacon">Bacon.<br>
<input type="checkbox" name="toppings" value="Artichoke">Artichoke.<br>
<input type="checkbox" name="toppings" value="Peanut Butter">Peanut butter.<br>
</div>
<button type="submit">Let's get your order</button>
</form>
<ul id="responses">
</ul>
</div>
</body>
</html>

Firstly, you need to get values of all checked toppings in an array, currently you are getting only the first one. Then you need to add prices for each topping selected while calculating the price. you can use indexOf for this:
var pizzaPrice = 0;
function Pizza(size,toppings,pizzaPrice) {
this.size = size;
this.toppings = toppings;
this.pizzaPrice = 0;
}
Pizza.prototype.price = function() {
if (this.size === "Small") {
this.pizzaPrice += 2;
}
else if (this.size === "Medium") {
this.pizzaPrice += 3;
}
else if (this.size === "Large") {
this.pizzaPrice += 4;
}
if (this.toppings.indexOf("Cheese") >= 0) {
this.pizzaPrice += 3;
}
if (this.toppings.indexOf("Peanut Butter") >= 0) {
this.pizzaPrice += 10;
}
if (this.toppings.indexOf("Vegetarian") >= 0) {
this.pizzaPrice += 2;
}
if (this.toppings.indexOf("Supreme") >= 0) {
this.pizzaPrice += 4;
}
if (this.toppings.indexOf("Pepperoni") >= 0) {
this.pizzaPrice += 3;
}
return this.pizzaPrice;
}
$(document).ready(function(){
$("form#pizza").submit(function(event){
event.preventDefault();
var size = $("input[type=radio][name=size]:checked").val();
var toppings = [];
$("input[type=checkbox][name=toppings]:checked").each(function(){
toppings.push($(this).val());
});
var newPizza = new Pizza(size,toppings,pizzaPrice);
newPizza.price();
$("#responses").append("<li>" + "You ordered a " + newPizza.size + " " + newPizza.toppings + " pizza. " + " Your total price is " + newPizza.pizzaPrice + "</li>");
});
});
<!DOCTYPE html>
<html>
<head>
<title>Pizza Pizza</title>
<link href="css/bootstrap.css" rel="stylesheet" type="text/css">
<link href="css/styles.css" rel="stylesheet" type="text/css">
<script src="js/jquery-3.2.0.js"></script>
<script src="js/scripts.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<div class="container">
<div class="jumbotron">
<h2>Pizza Toppings</h2>
</div>
<form id="pizza">
<div class="form-group">
<p>What size would you like your pizza:</p>
<input type="radio" name="size" value="Small">Small.<br>
<input type="radio" name="size" value="Medium">Medium.<br>
<input type="radio" name="size" value="Large">Large.<br>
</div>
<div class="form-group">
<p>Which toppings would you like</p>
<input type="checkbox" name="toppings" value="Cheese">Cheese.<br>
<input type="checkbox" name="toppings" value="Vegetarian">Vegetarian.<br>
<input type="checkbox" name="toppings" value="Supreme">Supreme.<br>
<input type="checkbox" name="toppings" value="Pepperoni">Pepperoni.<br>
<input type="checkbox" name="toppings" value="Fruit">Fruit.<br>
<input type="checkbox" name="toppings" value="Bacon">Bacon.<br>
<input type="checkbox" name="toppings" value="Artichoke">Artichoke.<br>
<input type="checkbox" name="toppings" value="Peanut Butter">Peanut butter.<br>
</div>
<button type="submit">Let's get your order</button>
</form>
<ul id="responses">
</ul>
</div>
</body>
</html>

The statement here
var toppings = $("input[type=checkbox][name=toppings]:checked").val();
is incorrect. As it is returning you the value of first checked checkbox.
Instead use following statement to get an array of checked values.
var toppings = $("input[type=checkbox][name=toppings]:checked").get();
Now while retrieving the values you can use the following:
(this.toppings.indexOf("Cheese") >= 0)
The indexOf() returns -1 if no matching results is found.
Hope this solves your problem.

There are a number of issues -
1.) When you do
var toppings = $("input[type=checkbox][name=toppings]:checked").val();
you already lost all the toppings except the first one. Instead you could use
var toppings = $("input[type=checkbox][name=toppings]:checked");
var i = 0;
var toppingVal;
while(i < toppings.length){
toppingVal += " "+(toppings[i]).value;
i++;
}
2.) When you are calculating the price, you make use of if..else..if blocks. How can you add up multiple toppings, only one block would execute. use only if
3.) As per my suggestion you would get a string of toppings seperated by a space(' '). So you cannot be using === for comparison. Use indexOf to find if the toppings string contains a specific topping.
Take a look at this fiddle
https://jsfiddle.net/8u67x4nm/1/ . Works fine.

Related

How do I create an outcome quiz using html and JavaScript?

I've been trying to create a quiz and all the examples of quizzes I can find are scored mathematically with numerical values set for each answer. This is my attempt to create a "What ____ are you?" outcome quiz. What am I missing to make this work or how can I fix this code to make it more efficient? Thanks.
Edit: The problem is that it doesn't display a result after submission.
<HTML>
<HEAD>
<TITLE>
Title Of Quiz
</TITLE>
</HEAD>
<BODY>
Title of Quiz
<!--Quiz itself will go here-->
<form action="/results" method="post">
<!--This is where the questions go-->
<b>Question 1<br></b>
<input TYPE="radio" NAME="a" VALUE="1">answer choice 1<br>
<input TYPE="radio" NAME="a" VALUE="2">answer choice 2<br>
<input TYPE="radio" NAME="a" VALUE="3">answer chocie 3<br><br>
<b>Question 2<br></b>
<input TYPE="radio" NAME="b" VALUE="1">answer choice 1<br>
<input TYPE="radio" NAME="b" VALUE="2">answer choice 2<br>
<input TYPE="radio" NAME="b" VALUE="3">answer choice 3<br><br>
<b>Question 3<br></b>
<input TYPE="radio" NAME="c" VALUE="1">Answer choice 1<br>
<input TYPE="radio" NAME="c" VALUE="2">answer choice 2<br>
<input TYPE="radio" NAME="c" VALUE="3">answer choice 3<br><br>
<input id ="submit" type="submit" value="Get Result!" onclick="return process();"><br><br>
</form>
<script LANGUAGE="JavaScript">
function process()
{
var result1 = 0;
var result2 = 0;
var result3 = 0;
var f = document.f;
var i = 0;
<!--This is where the question values go-->
for (i = 0; i < f.a.length; i++) if (f.a[i].checked) value = f.a[i].value;
if (value == "1") { result1++; }
if (value == "2") { result2++; }
if (value == "3") { result3++; }
for (i = 0; i < f.b.length; i++) if (f.b[i].checked) value = f.b[i].value;
if (value == "1") { result1++; }
if (value == "2") { result2++; }
if (value == "3") { result3++; }
for (i = 0; i < f.c.length; i++) if (f.c[i].checked) value = f.c[i].value;
if (value == "1") { result1++; }
if (value == "2") { result2++; }
if (value == "3") { result3++; }
var out = "result1";
i = result1;
if (result2 > i) { out ="result2"; i = result2; }
if (result3 > i) { out ="result3"; i = result3; }
location.href = out + ".shtml";
}
function err(msg, url, line)
{
location.href = "error.html";
}
</SCRIPT>
</BODY>
</HTML>

Trying to convert my JavaScript into JQuery

I'm trying to convert my Javascript code into JQuery but I know I did something wrong when calling the function. I'm having a tough time knowing exactly what to put when trying to call the radio elements by name.
Original Javascript works, but I'm not sure how to get the JQuery version to work.
Index HTML
<!DOCTYPE html>
<html lang="en">
<head>
<title>Disney Quiz</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" href="images/favicon.ico">
<link rel="stylesheet" href="css/normalize.css">
<link rel="stylesheet" href="css/main.css">
<link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">
<script src="scripts/quiz.js"></script>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script
</head>
<body>
<header><h1>Disney Quiz</h1></header>
<main>
<p>Click on the correct answer for each question and submit your results.</p>
<form>
<fieldset>
<legend>Trivia Questions</legend>
<label> Enter your Name</label> <input type="text" id="myText" name="fieldName" value=""><br>
<section id="radio1">
<p> Question 1) What was Walt Disney's first character he created?</p>
<input type="radio" name="question0" value="A">Oswald the Lucky Rabbit<br>
<input type="radio" name="question0" value="B">Donald Duck<br>
<input type="radio" name="question0" value="C">Mickey Mouse<br>
<input type="radio" name="question0" value="D">Goofy<br>
<p id="flag0"><p>
</section>
<section id="radio2">
<p> Question 2) Snow White was the first ____ to ever be produced successfully.</p>
<input type="radio" name="question1" value="A">Movie<br>
<input type="radio" name="question1" value="B">Live-Action<br>
<input type="radio" name="question1" value="C">Cel-animated Film<br>
<input type="radio" name="question1" value="D">Cartoon<br>
<p id="flag1"><p>
</section>
<section id="radio3">
<p> Question 3) Walt left a big impression when he had created ____ films for the U.S. government</p>
<input type="radio" name="question2" value="A">Peacemaker<br>
<input type="radio" name="question2" value="B">Political<br>
<input type="radio" name="question2" value="C">World War II<br>
<input type="radio" name="question2" value="D">Religious<br>
<p id="flag2"><p>
</section>
<section id="radio4">
<p> Question 4) Which of the following is true?</p>
<input type="radio" name="question3" value="A">Disney at first wanted to become a filmmaker<br>
<input type="radio" name="question3" value="B">Disney has made multiple controversial cartoons.<br>
<input type="radio" name="question3" value="C">Disney holds the record for most individual Oscar wins.<br>
<input type="radio" name="question3" value="D">Heart failure was the cause of Disney's death.<br>
<p id="flag3"><p>
</section>
<section id="radio5">
<p> Question 5) Which of the following has been rumored to happen to Walt Disney after his death?</p>
<input type="radio" name="question4" value="A">Faked his death<br>
<input type="radio" name="question4" value="B">Cremated<br>
<input type="radio" name="question4" value="C">Buried<br>
<input type="radio" name="question4" value="D">Cryogenically frozen<br>
<p id="flag4"><p>
</section>
<br>
<button type="button">Show Results</button>
<p id="results"></p>
</fieldset>
</form>
</main>
<aside>
</aside>
<footer> <p align="center"> Project 4 - Fall 2018 </p> </footer>
</body>
</html>
Original JavaScript
var answers = ["A","C","B","C","D"],
total = answers.length;
function getCheckedValue(radioName)
{
var radios = document.getElementsByName(radioName);
for (var y = 0; y < radios.length; y++)
{
if(radios[y].checked)
{
return radios[y].value;
}
}
}
function getScore()
{
var score = 0;
for (var i = 0; i < total; i++)
{
document.getElementById("flag"+i).innerHTML = "";
if(getCheckedValue("question"+i) == answers[i])
{
score += 1;
}
else if(getCheckedValue("question"+i) != answers[i])
{
document.getElementById("flag"+i).innerHTML = "Your answer is incorrect.";
}
}
return score;
}
function returnScore()
{
var x = document.getElementById("myText").value;
document.getElementById("results").innerHTML = x + ", your score is " + getScore() + "/" + total;
}
JQuery
var answers = ["A","C","B","C","D"],
total = answers.length;
$(function getCheckedValue()
{
var radios = $('[name="question"]');
for (var y = 0; y < radios.length; y++)
{
if(radios[y].checked)
{
return radios[y].value;
}
}
});
$(':button').on('click', function getScore()
{
var score = 0;
for (var i = 0; i < total; i++)
{
$("flag"+i).innerHTML = "";
if(getCheckedValue("question"+i) == answers[i])
{
score += 1;
}
else if(getCheckedValue("question"+i) != answers[i])
{
$("flag"+i).innerHTML = "Your answer is incorrect.";
}
}
return score;
});
$(function returnScore()
{
var x = $("myText").value;
$("results").innerHTML = x + ", your score is " + getScore() + "/" + total;
});
You don't need to put function definitions inside $(...), just put it at top-level just like in your plain JS version. $(...) is for code that needs to run after the DOM is loaded, but you don't need to wait to define functions. It will also call the functions you define there, not just define them.
The jQuery version of getCheckValue() isn't using the parameter, you need to add that.
And selectors for IDs need to begin with #.
function getCheckedValue(radioname)
{
return $(`[name="${radioname}"]:checked:first`).val();
}
In getScore your else if condition is the opposite of the if condition. So you should just use else. And jQuery uses the .html() and .text() functions to fill in an element, you don't assign to .innerHTML.
$(':button').on('click', function getScore()
{
var score = 0;
for (var i = 0; i < total; i++)
{
$("flag"+i).innerHTML = "";
if(getCheckedValue("question"+i) == answers[i])
{
score += 1;
}
else
{
$("#flag"+i).text("Your answer is incorrect.");
}
}
return score;
});
function returnScore()
{
var x = $("#myText").value;
$("#results").html(x + ", your score is " + getScore() + "/" + total);
}
In the HTML, you need to change the order that you load the scripts:
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="scripts/quiz.js"></script>
Since quiz.js uses jQuery, jQuery has to be loaded first.

JavaScript 'body onload=' fails to load function

I'm currently working on a website for a school project which involves HTML, JavaScript, and CSS. For my website I decided to do a dice roll simulation which would calculate and then show dice images randomized. The problem is that the JavaScript portion of the code fails to work at all. The code in the load function which is supposed to change the text in the test paragraph doesn't execute, which makes me think that the problem is occuring with the onload part of the body tag. However, because I'm fairly new to JavaScript I'm not sure what the exact problem is or how to fix it.
<!DOCTYPE html>
<html>
<head>
<link href='style.css' rel='stylesheet' type='text/css'/>
<meta charset='utf-8'/>
<script>
function loadFunction() {
document.getElementById('rolldice').onclick = rollDice;
document.getElementById('test').innerHTML = 'works';
}
function rollDice() {
var imgstrbase = 'diceimages/'
var dicenum = document.getElementById('numselect').value;
var dicetype = document.getElementById('diceselect').value;
var die1val = randNum(dicetype);
var die1imgstr = imgstrbase.concat(dicetype, String(dice1val), '.jpg');
if (dicenum >= 2) {
var die2val = randNum(dicetype);
var die2imgstr = imgstrbase.concat(dicetype, String(dice2val), '.jpg');
if (dicenum == 3) {
var die3val = randNum(dicetype);
var die3imgstr = imgstrbase.concat(dicetype, String(dice3val), '.jpg');
} else {
var die3imgstr = 'diceimages/grey.jpg';
}
} else {
var die2imgstr = 'diceimages/grey.jpg';
}
document.getElementById('die1img').src = die1imgstr;
document.getElementById('die2img').src = die2imgstr;
document.getElementById('die3img').src = die3imgstr;
}
function randNum(num) {
return Math.floor(Math.random() * num) + 1;
}
</script>
</head>
<body onload='loadFunction();'>
<p id='test'> original </p>
<h1> Dice Roll! </h1>
<form id='numselect'>
<input type='radio' name='list1' value=1 checked> One <br>
<input type='radio' name='list1' value=2> Two <br>
<input type='radio' name='list1' value=3> Three <br>
</form>
<button id='rolldice' type='button'> Roll Dice </button>
<form id='diceselect'>
<input type='radio' name='list2' value='six' checked> Six-Sided <br>
<input type='radio' name='list2' value='twenty'> Twenty-Sided <br>
</form>
<img src='diceimages/grey.jpg' id='die1img'>
<img src='diceimages/grey.jpg' id='die2img'>
<img src='diceimages/grey.jpg' id='die3img'>
</body>
</html>
For reference the dice images are called 'six1.jpg', 'six2.jpg', 'six3.jpg', 'six4.jpg', 'six5.jpg', and 'six6.jpg'. I haven't yet added the twenty-sided die images.
Typo - die1val1 instead of dice1val1
var dice1val = randNum(dicetype);
should be
var die1val = randNum(dicetype);
<!DOCTYPE html>
<html>
<head>
<link href='style.css' rel='stylesheet' type='text/css'/>
<meta charset='utf-8'/>
<script>
function loadFunction() {
document.getElementById('rolldice').onclick = rollDice;
document.getElementById('test').innerHTML = 'works';
}
function rollDice() {
var imgstrbase = 'diceimages/'
var dicenum = document.getElementById('numselect').value;
var dicetype = document.getElementById('diceselect').value;
var die1val = randNum(dicetype);
var die1imgstr = imgstrbase.concat(dicetype, String(die1val), '.jpg');
if (dicenum >= 2) {
var die2val = randNum(dicetype);
var die2imgstr = imgstrbase.concat(dicetype, String(die2val), '.jpg');
if (dicenum == 3) {
var die3val = randNum(dicetype);
var die3imgstr = imgstrbase.concat(dicetype, String(die3val), '.jpg');
} else {
var die3imgstr = 'diceimages/grey.jpg';
}
} else {
var die2imgstr = 'diceimages/grey.jpg';
}
document.getElementById('die1img').src = die1imgstr;
document.getElementById('die2img').src = die2imgstr;
document.getElementById('die3img').src = die3imgstr;
}
function randNum(num) {
return Math.floor(Math.random() * num) + 1;
}
</script>
</head>
<body onload='loadFunction();'>
<p id='test'> original </p>
<h1> Dice Roll! </h1>
<form id='numselect'>
<input type='radio' name='list1' value=1 checked> One <br>
<input type='radio' name='list1' value=2> Two <br>
<input type='radio' name='list1' value=3> Three <br>
</form>
<button id='rolldice' type='button'> Roll Dice </button>
<form id='diceselect'>
<input type='radio' name='list2' value='six' checked> Six-Sided <br>
<input type='radio' name='list2' value='twenty'> Twenty-Sided <br>
</form>
<img src='diceimages/grey.jpg' id='die1img' alt='die1'>
<img src='diceimages/grey.jpg' id='die2img' alt = 'die2'>
<img src='diceimages/grey.jpg' id='die3img' alt = 'die3'>
</body>
</html>

Javascript - how do i add cost?

How would i add a cost for the check boxes. When i add a onClick it said myFunction was not defined. I Don't know what i am doing. I was trying to make a check with the second function so if it was checked it would add the costs together and make a subtotal but i cant get it to work or find a way to get the costs to be a value in the check boxes
<html>
<body>
<p>A pizza is 13 dollars with no toppings.</p>
<form action="form_action.asp">
<input type="checkbox" name="pizza" value="Pepperoni" id="pep" > Pepperoni + 5$<br>
<input type="checkbox" name="pizza" value="Cheese" id="ch" >Cheese + 4$<br>
<br>
<input type="button" onClick="myFunction()" value="Send order"><br>
<input type="button" onClick="cost()" value="Get cost" > <br>
<input type="text" id="order" size="50">
</form>
<script type="text/javascript">
function myFunction() {
var pizza = document.forms[0];
var txt = "";
var i;
for (i = 0; i < pizza.length; i++) {
if (pizza[i].checked) { // this shows the you ordered the pizza with blank topping
txt = txt + pizza[i].value + " ";
}
}
document.getElementById("order").value = "You ordered a pizza with: " + txt;
}
function cost() {
var x = document.getElementById(pep).checked; // this is the failed check and i dont know how to fix it and get it to add a cost
document.getElementById("demo").innerhtml = x;
}
</script>
<p id="demo"></p>
</body>
</html>
answer that https://stackoverflow.com/users/7488236/manish-poduval got
<html>
<body>
<p>A pizza is 13 dollars with no toppings.</p>
<form action="form_action.asp">
<input type="checkbox" name="pizza" value="Pepperoni" id="pep">Pepperoni + 5$<br>
<input type="checkbox" name="pizza" value="Cheese" id="che">Cheese + 4$<br>
<br>
<input type="button" onclick="myFunction()" value="Send order">
<input type="button" onclick="cost()" value="Get cost">
<br><br>
<input type="text" id="order" size="50">
</form>
<script>
function myFunction() {
var pizza = document.forms[0];
var txt = "";
var i;
for (i = 0; i < pizza.length; i++) {
if (pizza[i].checked) {
txt = txt + pizza[i].value + " ";
}
}
document.getElementById("order").value = "You ordered a pizza with: " + txt;
}
function cost() {
var pep = 5;
var che = 4;
var pizza = 13;
var total = 0;
if (document.getElementById("pep").checked === true) {
total += pep;
}
if (document.getElementById("che").checked === true) {
total += che;
}
document.getElementById("order").value = "The cost is : " + total;
}
</script>
</body>
</html>
document.getElementById("pep").checked;
You have not written this line properly. after this check the value of x if it is true then add the value 5$ to 13$ and sum it up the cost and display it on a text field.
Let me know if it works or not.

Multiplying text put value with the sum of check box values and display it on a paragraph

I'm trying to multiply the entered text input value with the sum of check box values clicked. So far when you click the check boxes the sumof their avues is displayed instantly on the span emlement with id="Totalcost"....i need some help figuring out how i could multiply the sum of check box selected with the value entered in the text input field.
If it can be easily done using JQuery i will really appreciate
Thanks in advance.
Here is my code
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript">
var total = 0;
inputBox.onkeyup = function(){
document.getElementById('Totalcost').innerHTML = inputBox.value;
}
function test(item){
var inputBox = document.getElementById('chatinput');
if(item.checked){
total+= parseInt(item.value);
}else{
total-= parseInt(item.value);
}
//alert(total);
document.getElementById('Totalcost').innerHTML = total ;
}
</script>
</head>
<body>
<input type="text" id="chatinput" onchange="myFunction()"><br>
<p id="printchatbox"></p>
<div id="container">
<p id="printc"></p>
<input type="checkbox" name="channcost" value="10" onClick="test(this);" />10<br />
<input type="checkbox" name="chanlcost" value="20" onClick="test(this);" />20 <br />
<input type="checkbox" name="chancost" value="40" onClick="test(this);" />40 <br />
<input type="checkbox" name="chanlcost" value="60" onClick="test(this);" />60 <br />
</div>
Total Amount : <span id="Totalcost"> </span><BR><BR><BR>
</body>
</html>
You have many incongruences in your code.....
Replace it with this:
<!DOCTYPE HTML>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript">
var total = 0;
function test(){
var checkboxes = document.getElementById('container').getElementsByTagName("input");
var box_value = parseInt(document.getElementById('chatinput').value);
var new_total = 0;
for(var i=0; i<checkboxes.length; i++){
var item = checkboxes[i];
if(item.checked){
new_total += parseInt(item.value);
}
}
if(box_value>0){ total = (new_total>0?new_total:1) * box_value; }
else{ total = new_total; }
document.getElementById('Totalcost').innerHTML = total ;
}
</script>
</head>
<body>
<input type="text" id="chatinput" onchange="test()"><br>
<p id="printchatbox"></p>
<div id="container">
<p id="printc"></p>
<input type="checkbox" name="channcost" value="10" onClick="test();" />10<br />
<input type="checkbox" name="chanlcost" value="20" onClick="test();" />20 <br />
<input type="checkbox" name="chanlcost" value="40" onClick="test();" />40 <br />
<input type="checkbox" name="chanlcost" value="60" onClick="test();" />60 <br />
</div>
Total Amount : <span id="Totalcost"> </span><BR><BR><BR>
</body>
</html>
I changed your script to make these changes
var total = 0;
function test(item){
var inputBox = document.getElementById('chatinput');
if(item.checked){
total+= parseInt(item.value);
}else{
total-= parseInt(item.value);
}
inputValue = $("#chatinput").val();
textValue = (isNaN(inputValue)) ? 1 : parseInt(inputValue);
if(textValue == "NaN"){
textValue = 1;
}
totalAfterMul = total*textValue;
console.log(totalAfterMul);
document.getElementById('Totalcost').innerHTML = totalAfterMul ;
}
It will do what is desired.
It takes the input value and then multiply it with the sum of the check boxes. If the input value is not a number then it will consider it as 1
inputValue = $("#chatinput").val();
textValue = (isNaN(inputValue)) ? 1 : parseInt(inputValue);
if(textValue == "NaN"){
textValue = 1;
}
totalAfterMul = total*textValue;

Categories