Javascript add value if checkbox is checked - javascript

<p>
<label for="hours">Learn JavaScript the Hardy Way’ - Complete e-book (Printed)</label>
<input type="number" min="0" id="chap7" name="hours" value="0">
</p>
<input type="checkbox" id="printed"/>Please tick if you would like a printed version<br />
<p class="post">Postage : <strong>£<output id="post">0</output></strong><p>
I would like a piece of javascript so that upon the checkbox being checked, it makes the postage value 3.50. However, it is 3.50 per copy of the complete ebook. So it would have to check the value of number box and times it by the value inside.

Solution that changes based on checkbox state:
var chap7 = document.getElementById('chap7'),
post = document.getElementById('post'),
printed = document.getElementById('printed');
printed.addEventListener('change', function() {
var quantity = parseInt(chap7.value, 10);
post.value = printed.checked ? quantity * 3.5 : quantity;
}, false);
chap7.addEventListener('change', function() {
post.value = parseInt(this.value, 10);
});
<p>
<label for="hours">Learn JavaScript the Hardy Way’ - Complete e-book (Printed)</label>
<input type="number" min="0" id="chap7" name="hours" value="0">
</p>
<input type="checkbox" id="printed"/>Please tick if you would like a printed version<br />
<p class="post">Postage : <strong>£<output id="post">0</output></strong><p>
Solution that changes based on text input state:
var chap7 = document.getElementById('chap7'),
post = document.getElementById('post');
chap7.addEventListener('change', function(e) {
var quantity = parseInt(chap7.value, 10);
post.value = quantity * 3.5;
}, false);
<p>
<label for="hours">Learn JavaScript the Hardy Way’ - Complete e-book (Printed)</label>
<input type="number" min="0" id="chap7" name="hours" value="0">
</p>
<p class="post">Postage : <strong>£<output id="post">0</output></strong><p>

Related

Combinig output of 2 function in javascript

I am relatively new to Javascript (biopython background) and I am trying to add a simple feature to a website.
In essence, I need to accept user input for 4 types of menus (check boxes) and then multiply the sum of the values ($) of selected menus by the number of days and number of people (user inputs using text fields).
Below are HTML and Javascript parts of the code
function multiply() {
var n_ppl = document.getElementsByName('people')[0].value;
var n_days = document.getElementsByName('days')[0].value;
return var out = n_ppl * n_days;
}
function totalIt() {
var n_ppl = document.getElementsByName('people')[0].value;
var n_days = document.getElementsByName('days')[0].value;
var input = document.getElementsByName("product");
var total = 0;
for (var i = 0; i < input.length; i++) {
if (input[i].checked) {
total += parseInt(input[i].value);
}
return var price = total
}
// not sure how can I get - var final = total * out
// after I get it I can finally do - document.getElementsByName("total")[0].value = "$" + final.toFixed(2);
<br> Breakfast <input name="product" value="12" type="checkbox" onclick="totalIt()" /> <br>
<br> First Meal <input name="product" value="20" type="checkbox" onclick="totalIt()" /> <br>
<br> Second Meal <input name="product" value="15" type="checkbox" onclick="totalIt()" /> <br>
<br> Craft Service <input name="product" value="10" type="checkbox" onclick="totalIt()" /> <br>
<br> Number of People <input type="text" name="people"> <br>
<br> Number of Days <input type="text" name="days"> <br>
<br> Total: <input value="$0.00" readonly="readonly" type="text" name="total" />
I apologize to all web developers for my pythonic style in advance.
I should also mention that both functions work perfectly fine separately but even without trying to multiply their outputs (i.e. even if their code is present next to each other), nothing works.
I will be really grateful for your help!
You need only one function to iterate over your inputs.
Do not use inline JavaScript it's sign of bad coding habits, and makes the application hard to debug. Keep your JS in one place and make use of Element.addEventListener()
Use Node.querySelector() and Node.querySelectorAll()
Use name="product[]" syntax when handling similar names. This will be submitted to the backend as an array of values.
You can use Array.prototype.reduce() to reduce (accumulate) all your '[name="product[]"]:checked' chechboxes values to a single integer
Place your <script> code right before the closing </body> tag
const EL_menu = document.querySelector("#menu");
const calcPrice = evt => {
const price = [...EL_menu.querySelectorAll('[name="product[]"]:checked')]
.reduce((n, el) => (n += +el.value, n), 0);
const nPers = +EL_menu.querySelector('[name="people"]').value || 1;
const nDays = +EL_menu.querySelector('[name="days"]').value || 1;
const total = price * nPers * nDays;
EL_menu.querySelector("[name=total]").value = `\$${total.toFixed(2)}`;
}
EL_menu.querySelectorAll("input").forEach(el => el.addEventListener('input', calcPrice));
#menu label { display: block; }
<div id="menu">
<label><input type="checkbox" name="product[]" value="12"> Breakfast</label>
<label><input type="checkbox" name="product[]" value="20"> First Meal</label>
<label><input type="checkbox" name="product[]" value="15"> Second Meal</label>
<label><input type="checkbox" name="product[]" value="10"> Craft Service</label>
<label><input type="number" name="people" value="1" min="1"> Number of People</label>
<label><input type="number" name="days" value="1" min="1"> Number of Days</label><br>
Total: <input type="text" name="total" value="$0.00" readonly="readonly">
</div>

When checkbox is selected multiply textbox value by 0.9

I have a non-clickable textbox that I am using to keep a running total (everytime a checkbox is clicked, it's value is being added to the textbox).
I am struggling however with doing some multiplication on this textbox value. I have a checkbox that, when selected, I would like to multiply by 0.9 (to simulate a 10% discount). How would I go about doing this?
Here's what I have so far (but is not working - textbox value just goes to 0.00):
$(document).ready(function($) {
var sum = 0;
$('input[id=10percent]').click(function() {
sum = 0;
$('input[id=15percent]:checked').each(function() {
debugger;
var val = parseFloat($(this).val());
sum * 0.9;
});
$('#sum').val(sum.toFixed(2));
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="runningtotal">
Running CPC Total (in £): <input id='sum' type='text' readonly />
</div>
HTML (for radio boxes):
<div class="agencydiscount">
<h1>Agency Discount</h1>
<input type="radio" name="percentdiscount" value="0.00">None<br>
<input type="radio" name="percentdiscount" id="10percent" value="0.00">10% Discount<br>
<input type="radio" name="percentdiscount" id="15percent" value="0.00">15% Discount<br>
</div>
jQuery:
jQuery to update running total textbox:
jQuery(document).ready(function($) {
var sum = 0;
$('input[type=checkbox]').click(function() {
sum = 0;
$('input[type=checkbox]:checked').each(function() {
debugger;
var val = parseFloat($(this).val());
sum += val;
});
$('#sum').val(sum.toFixed(2));
});
});
Your JS seems a little confused. You're attaching only one event handler and trying to loop over an unrelated selector that contains only a single element. You're also multiplying the value but not assigning the result to anything.
To make this work you need to attach the event handler to all the radio buttons. Then you can use the value property of all the radios to hold the number to multiply the #sum by to get the discounted total.
Also note that you need somewhere to store the original total, ie. the value before any discount is applied, so that the calculation always works from the base figure. You can use a data attribute for this, but note that you must update this attribute along with the value.
With all that said, try this:
jQuery(function($) {
$('input[name="percentdiscount"]').on('change', function() {
applyDiscount();
});
$('input[type=checkbox]').click(function() {
let sum = 0;
$('input[type=checkbox]:checked').each(function() {
sum += parseFloat($(this).val());
});
$('#sum').val(sum.toFixed(2)).data('total', sum);
applyDiscount();
});
function applyDiscount() {
var pc = parseFloat($('input[name="percentdiscount"]:checked').val());
$('#sum').val(function() {
return ($(this).data('total') * pc).toFixed(2);
});
}
});
label {
display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label>
<input type="checkbox" value="10.00">
£10.00
</label>
<label>
<input type="checkbox" value="5.00">
£5.00
</label>
<label>
<input type="checkbox" value="19.99">
£19.99
</label>
<div class="runningtotal">
Running CPC Total (in £): <input id="sum" type="text" readonly="true" value="0.00" data-total="0" />
</div>
<div class="agencydiscount">
<h1>Agency Discount</h1>
<label>
<input type="radio" name="percentdiscount" value="1" checked>
None
</label>
<label>
<input type="radio" name="percentdiscount" id="10percent" value="0.9">
10% Discount
</label>
<label>
<input type="radio" name="percentdiscount" id="15percent" value="0.85">
15% Discount
</label>
</div>
As an aside, I would suggest researching the basics of JS as there's some fundamental principles you need to get a firm grasp of. This MDN guide is a great starter.
You must use their name instead of using their id. So your code must be like this:
$(document).ready(function($) {
$('input[type=radio]').on('change', function() {
var sum = $('input[name=percentdiscount]:checked').attr('value') * 0.9;
$('#sum').val(sum.toFixed(2));
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="runningtotal">
Running CPC Total (in £): <input id='sum' type='text' readonly />
</div>
<div class="agencydiscount">
<h1>Agency Discount</h1>
<input type="radio" name="percentdiscount" value="0.00">None<br>
<input type="radio" name="percentdiscount" id="10percent" value="10.00">10% Discount<br>
<input type="radio" name="percentdiscount" id="15percent" value="20.00">15% Discount<br>
</div>

Can't get Jquery to write the output of a function to html

new guy here. I have a feeling this is an extremely basic question but I can't get this Jquery code to write the output of the function to html and have it show up. I believe it's an issue with the script but unsure if I am doing something wrong with html as well.
The goal of this function is to create a calculator that gives future investment value based on what the user inputs. When I click submit, It used to change all of the html to show just 'NaN' but now when I click the submit button, it clears the input boxes but does not give me any number or any answer even though I believe I've set it to display the number to
HTML
<body>
<div id = "futurevalue">
<form>
<input type="radio" name="formula" value="future_investment" checked>Future Investment<br>
<label for="princeple">Enter the princeple amount invested:</label>
<input id="princeple" type="number" name="princeple" step="0.01"><br>
<label for="time">Enter how long the investment will be for (in years):</label>
<input id='time' type='number' name='time'><br>
<label for='rate'>Enter the expected interest rate:</label>
<input id='rate' type="number" name='rate'><br>
<input id='submit' type='submit' name='submit'>
</form>
<p>Total:</p>
<p id='result'></p>
</div>
jQuery
$('#submit').click(function(){
$('#result').html(function(){
return toString(output,10);
});
});
var princeple = parseInt($('#princeple'),10);
var time = parseInt($('#time'),10);
var rate = parseInt($('#rate'),10);
var output = (princeple * time + rate);
Here is your fix:
$('#submit').click(function(){
var princeple = parseInt($('#princeple').val());
var time = parseInt($('#time').val());
var rate = parseFloat($('#rate').val()/100);
var output = ((princeple * rate) * time);
$('#result').html(output);
//prevent from page reload
return false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id = "futurevalue">
<form>
<input type="radio" name="formula" value="future_investment" checked>Future Investment<br>
<label for="princeple">Enter the princeple amount invested:</label>
<input id="princeple" type="number" name="princeple" step="0.01"><br>
<label for="time">Enter how long the investment will be for (in years):</label>
<input id='time' type='number' name='time'><br>
<label for='rate'>Enter the expected interest rate:</label>
<input id='rate' type="number" name='rate'><br>
<input id='submit' type='submit' name='submit'>
</form>
<p>Total:</p>
<p id='result'></p>
</div>
You have to calculate the value inside the click event and assign to the result. The formula for calculating interest is also incorrect.
Try the following code, basically you need:
Calculate your variables inside cb click and than output the resut in your div #result. Use .val to get values for your inputs and event.preventDefault() to avoid form submit (which is the browser default behavior).
$('#submit').click(function(event) {
var princeple = parseInt($('#princeple').val(), 10);
var time = parseInt($('#time').val(), 10);
var rate = parseInt($('#rate').val(), 10);
var output = (princeple * time + rate);
$('#result').html(output);
event.preventDefault();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="futurevalue">
<form>
<input type="radio" name="formula" value="future_investment" checked>Future Investment<br>
<label for="princeple">Enter the princeple amount invested:</label>
<input id="princeple" type="number" name="princeple" step="0.01"><br>
<label for="time">Enter how long the investment will be for (in years):</label>
<input id='time' type='number' name='time'><br>
<label for='rate'>Enter the expected interest rate:</label>
<input id='rate' type="number" name='rate'><br>
<input id='submit' type='submit' name='submit'>
</form>
<p>Total:</p>
<p id='result'></p>
</div>

jquery - sum of all checkbox value * their unique textbox value

i need sum of (every check box value X its textbox value)
<input name="33" value="280000" onclick="test(this);" type="checkbox">
<input id="33" style="width:20px;float: left; text-align: center" type="text">
example:
fist checkbox value = 20 X its textbox value = 10
second checkbox value = 5 X its textbox value = 2
my answer = 20*10 + 5*2 = 210 (ok)
also i need when checkbox value changes my answer change, without click.
const totalBox = document.getElementById("total")
document.querySelectorAll("input[type=text]").forEach((input) => input.addEventListener("input", calculate))
document.querySelectorAll("input[type=checkbox]").forEach((input) => input.addEventListener("change", calculate))
function calculate() {
const checkboxes = document.querySelectorAll("input[type=checkbox]")
let total = 0
for (let checkbox of checkboxes) {
if (checkbox.checked) {
total += Number(checkbox.value) * Number(document.getElementById(checkbox.name).value)
}
}
totalBox.textContent = total
}
calculate()
<input name="33" value="280000" type="checkbox" checked>
<input id="33" value="10" type="text">
<br/>
<input name="34" value="150000" type="checkbox">
<input id="34" value="15" type="text">
<h2>Total: <span id="total"></span></h2>
Here you go with the solution https://jsfiddle.net/yuhpbz47/
var total = 0;
$('button[type="submit"]').click(function(){
$('input[type="checkbox"]').each(function(){
if($(this).is(':checked')){
total += $(this).val() * (parseInt($(this).next().val()) || 0 );
}
});
console.log(total);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" value="10" />
<input type="text" />
<br/>
<input type="checkbox" value="20"/>
<input type="text" />
<button type="submit">
Submit
</button>
If they are always grouped by two you can simply take all inputs, multiply every pairs value and add it up:
var result = Array.from(document.getElementsByTagName("input")).reduce(function(result,el,i,arr){
return result+i%2?el.value*(arr[i-1].checked?arr[i-1].value:0):0;
},0);
for shure this can be executed inside an onchange handler.
http://jsbin.com/muvigedodu/edit?js
You are trying to achieve, when a check box is clicked a value is multiplied by the value of the input check box then for all check box give us the sum right? if so this below code which is well documented should help out with it
Observe the pattern i used to get the multiply value so it can be dynamic
Hope it helps.
$(document).ready(
function(){
/**
* this is used to update our view so you see what we are * doing currently now
*/
function updateView(value){
$("#view").html(value);
}
$(".sum").click(function(event){
//we get our value to multiply our value with
var multiply = $(this).attr("multiply");
var value = $(this).val();
//we multiply here
var answer = multiply*value;
//we sum up this value with the sum in the hidden fied if checked else substract
var sumField = $("#sum");
if($(this).is(':checked')){
sumField.val(Number(sumField.val())+answer);
}else{
sumField.val(Number(sumField.val())-answer);
}
//update our view
updateView(sumField.val());
});
}
);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Check boxes
<br>
1. <input type="checkbox" value="10" multiply="20" class="sum"> value 10, multiply 20 <br>
2. <input type="checkbox" value="5" multiply="10" class="sum"> value 5, multiply 10 <br>
3. <input type="checkbox" value="3" multiply="5" class="sum"> value 3, multiply 5 <br>
<input type="hidden" value="0" id="sum">
value: <div id="view">
</div>

jQuery & JavaScript Excercise: Adding Values On Condition

How do you make it calculate using JavaScript/jQuery based on condition:
on radio button 'change' event.
if user clicks "Yes" or "N/A", the value of text boxes with default values next to it will be added and reflected in Total
HTML:
<form>
<fieldset>
<input type="radio" name="remark[]" value="Yes" class="answer">Yes
<input type="radio" name="remark[]" value="No" class="answer">No
<input type="radio" name="remark[]" class="answer">N/A
<input type="text" name="point1" class="score" value="3">
</fieldset>
<fieldset>
<input type="radio" name="remark[]" value="Yes" class="answer">Yes
<input type="radio" name="remark[]" value="No" class="answer">No
<input type="radio" name="remark[]" class="answer">N/A
<input type="text" name="point2" class="score" value="2">
</fieldset>
Total<input type="text" name="total" class="result">
</form>
Vanilla Javascript
Note: these scripts associate with forms that have the class name calc
This script will associate with the form, so if you have multiple instances each form will calculate separately.
Basically for each form select all input's with a value of 'Yes' which are checked, then find the score for that field set and add it to the total
(Demo)
(function(){
"use strict";
function calculate() {
var forms = document.querySelectorAll('.calc'), form, i;
for (i = 0; form = forms[i]; i++) {
var total = 0;
var inputs = form.querySelectorAll('input[value="Yes"]:checked'), input, x;
for (x = 0; input = inputs[x]; x++) {
total += parseFloat(input.parentElement.lastElementChild.value);
}
form.lastElementChild.value = total;
}
}
calculate();
var inputs = document.querySelectorAll('.calc input'), input, x;
for(x = 0; input = inputs[x]; x++) {
input.onchange = calculate;
}
})();
jQuery
If you would like to use jQuery, this is the same script converted to jQuery
(Demo)
(function(){
"use strict";
function calculate() {
$('.calc').each(function(){
var total = 0;
$('input[value="Yes"]:checked', this).each(function(){
total += parseFloat($('input.score', this.parentElement).val());
});
$('input.result', this).val(total);
});
}
calculate();
$('.calc input').on('change', calculate);
})();
Not sure if I understand correctly, but first you'll need a few changes in your markup, radio groups should have different name so it'll be like remark[0] for first group and remark[1] for the second and so on. The "N/A" radios don't seem to have a value so I've added value="NA" to them. So your HTML will look like:
<form>
<fieldset>
<input type="radio" name="remark[0]" value="Yes" class="answer" />Yes
<input type="radio" name="remark[0]" value="No" class="answer" />No
<input type="radio" name="remark[0]" value="NA" class="answer" />N/A
<input type="text" name="point1" class="score" value="3" />
</fieldset>
<fieldset>
<input type="radio" name="remark[1]" value="Yes" class="answer" />Yes
<input type="radio" name="remark[1]" value="No" class="answer" />No
<input type="radio" name="remark[1]" value="NA" class="answer" />N/A
<input type="text" name="point2" class="score" value="2" />
</fieldset>Total
<input type="text" name="total" class="result" />
</form>
Then we just listen to radio's onchange and if Yes or N/A is selected for each group, we have it's value to the total. I used parseInt on values since they're string and it seemed the values were supposed to work as numbers. (2+3 should be 5 and not 23).
$('form input[type=radio]').on('change', function() {
var total = 0;
$('form fieldset').each(function(i) {
var point = parseInt($(this).find('input[type=text]').val());
var val = $(this).children('[name="remark[' + i + ']"]:checked').val();
if(val == "Yes" || val == "NA")
total += point;
});
$('input[name="total"]').val(total);
});
jsfiddle DEMO

Categories

Resources