Multiplying a text input by selected radio button - javascript

Hi i am new to javascript and having some trouble.
I need my function to take the user input "recserv" and multiply it by the value of the selected radio button, as well as update if the value is changed or the radio button is changed.
Changing the radio buttons seems to work, but I get an error when the "recserv" value is changed.
Thank you for any help!
<script>
function yeartot(service) {
var recserv = parseFloat(document.getElementById('recserv').value);
document.getElementById("result").value = service*recserv;
}
</script>
<body>
<p>Select the frequency</p>
<input onclick="yeartot(this.value)" type="radio" name="service" value="11">Monthly<br>
<input onclick="yeartot(this.value)" type="radio" name="service" value="6" checked> Bi-Monthly<br><br>
Recurring Service Amount <input onchange="yeartot()" id="recserv" value=0><br/><br/>
Total for year <input type="text" id="result">

The reason why you are getting NaN is because in your #recserv element's inline JS, you are not passing any value into the function when calling it. Therefore, you are multiplying with undefined which gives you a NaN value.
A quick fix to your issue will simply be letting the method itself retrieve the checked value of your input, and removing the need to pass any arguments to it. This is, however, a quick fix and I would never recommend using inline JS: check the next example for a proper solution.
function yeartot() {
var recserv = +document.getElementById('recserv').value;
var checkedService = +document.querySelector('input[name="service"]:checked').value;
document.getElementById("result").value = checkedService * recserv;
}
<p>Select the frequency</p>
<input onclick="yeartot()" type="radio" name="service" value="11">Monthly<br>
<input onclick="yeartot()" type="radio" name="service" value="6" checked> Bi-Monthly<br><br> Recurring Service Amount <input onchange="yeartot()" id="recserv" value=0><br/><br/> Total for year <input type="text" id="result">
Proposed solution: I suggest that you:
Use .addEventListener to listen to changes to your input elements. You can use document.querySelectorAll([selector]) to select the inputs that you want to bind the oninput event listener to. The callback will simply invoke yeartot()
Invoke yeartot() at runtime, so that you get calculated values when the document is loaded.
function yeartot() {
var recserv = +document.getElementById('recserv').value;
var checkedService = +document.querySelector('input[name="service"]:checked').value;
document.getElementById("result").value = checkedService * recserv;
}
document.querySelectorAll('#recserv, input[name="service"]').forEach(function(el) {
el.addEventListener('change', function() {
yeartot();
});
});
// Also, might want to run the first round of computation onload
yeartot();
<p>Select the frequency</p>
<input type="radio" name="service" value="11">Monthly<br>
<input type="radio" name="service" value="6" checked> Bi-Monthly<br><br> Recurring Service Amount <input id="recserv" value=0><br/><br/> Total for year <input type="text" id="result">

simply this...
document.getElementById('my-form').addEventListener('input', function () {
this.result.textContent = parseFloat(this.recserv.value) * parseInt(this.service.value)
})
<form id="my-form" onsubmit="return false">
<p>Select the frequency</p>
<input type="radio" name="service" value="11">Monthly
<br>
<input type="radio" name="service" value="6" checked> Bi-Monthly
<br><br>
Recurring Service Amount <input name="recserv" value="0">
<br /><br />
Total for year <output name="result"></output>
</form>
-- adding a form makes things easier if each entry (or output) has a name.
-- using a form element, you do not need to use any ID, and you do not need to see which radio button is checked, you directly take the selected value
-- and do not use a change event but use input event

const setup = () => {
const serviceInputs = document.querySelectorAll('input[name="service"]');
serviceInputs.forEach(e => e.addEventListener('click', yeartot));
const recserv = document.querySelector('#recserv');
recserv.addEventListener('change', yeartot);
}
const yeartot = (service) => {
const checkedInput = document.querySelector('input:checked');
const recserv = document.querySelector('#recserv');
const serviceNumber = parseFloat(checkedInput.value, 10);
const recservNumber = parseFloat(recserv.value, 10);
const result = document.querySelector('#result');
result.value = serviceNumber * recservNumber;
}
//load
window.addEventListener('load', setup);
<body>
<p>Select the frequency</p>
<input type="radio" name="service" value="11">Monthly<br>
<input type="radio" name="service" value="6" checked> Bi-Monthly<br><br>
Recurring Service Amount <input id="recserv" value="0"><br/><br/>
Total for year <input type="text" id="result">
</body>

yeartot method has a parameter and when you use yeartot() in onchange property of input cause undefined value in service parameter.undefined value is not a number and take error.

Change your script into this
<script>
const input = document.getElementById("recserv");
const result = document.getElementById("result");
function yeartot(service) {
const checkedService = document.querySelector(":checked");
var recserv = Number(document.getElementById("recserv").value);
document.getElementById("result").value =
Number(checkedService.value) * Number(input.value);
}
</script>

Related

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>

How to get the value of checkboxes in the order they are selected?

hope you can help me :)
I have this code to get the value of the checkboxes:
function check() {
var Input = Array.prototype.slice.call(document.querySelectorAll(".checkboxes:checked")).map(function(el) {
return el.value;
}).join(',')
document.getElementById('output2').innerHTML = Input;
return false;
}
I want that the output is in the order I selected the checkboxes. Is there a way to get them in correct order?
You can set the timestamp to them when they are changed (comments inline)
var allCheckboxes = document.querySelectorAll("input[type='checkbox'][data-name]");
//bind the event to set time value on change
[...allCheckboxes].forEach(s => s.addEventListener("change", function(e) {
e.currentTarget.timeval = new Date().getTime();
}));
document.querySelector("button").addEventListener("click", check);
function check() {
var output = [...allCheckboxes]
.filter(s => s.checked) // filter out non-checked
.sort((a, b) => a.timeval - b.timeval) //sort by timeval
.map(s => s.getAttribute("data-name")).join(","); //fetch only data-name for display
document.getElementById('output').innerHTML = output;
}
Check 1 <input type="checkbox" data-name="check1"> <br/> Check 2 <input type="checkbox" data-name="check2"> <br/> Check 3 <input type="checkbox" data-name="check3"> <br/> Check 4 <input type="checkbox" data-name="check4"> <br/> Check 5 <input type="checkbox"
data-name="check5"> <br/>
<button>check</button>
<div id="output"></div>
You can set an array and save the values as they are selected.
You can achive this by giving each chcekbox an event listener.
In the event listener you add an if to validate if the click event was when checked and then add them to your list/array.
Hope this helps :)
var checks = document.querySelectorAll('input[type=checkbox]');
var order = [];
for(var i=0; i<checks.length;i++){
checks[i].addEventListener("click", function(){
if(this.checked)
order.push(this.value);
})
}
<input type="checkbox" value="A">A
<input type="checkbox" value="B">B
<input type="checkbox" value="C">C
<input type="checkbox" value="D">D
<br>
<button onclick="console.log('Order: '+order)">Check order</button>
You can add a data-id attribute to each section. And when you click on one checkbox, change the attribute values of each checkbox to a serial number. To do this, it's easier to use jquery
You could use a Set and add or delete depending of the checked state of the check box.
Set returns the items in insertation order.
var checks = document.querySelectorAll('input[type=checkbox]'),
order = new Set,
i
for (i = 0; i < checks.length; i++) {
checks[i].addEventListener("click", function() {
order[['delete', 'add'][+this.checked]](this.value);
});
}
<input type="checkbox" value="A">A
<input type="checkbox" value="B">B
<input type="checkbox" value="C">C
<input type="checkbox" value="D">D
<br>
<button onclick="console.log('Order: '+[...order])">Check order</button>

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>

Store input radio selections when submit is clicked

I need to store in my js file which radio option for each radio name was selected as well as store the Username that was entered. Here is my form
<form id="newPlayer">
Username:<br>
<input type="text" name="user"/><br>
Please Choose a Class: <br>
<input type="radio" name="class"/>Archer
<input type="radio" name="class"/>Mage
<input type="radio" name="class"/>Warrior
<br>
Please Choose a Race: <br>
<input type="radio" name="race"/>Orc
<input type="radio" name="race"/>Elf
<input type="radio" name="race"/>Human
<input type="radio" name="race"/>Worg
<br>
<input type="submit" value="Submit">
</form>
EDIT:
When I try to target the submit button for a click function it causes my page to reload instead of making the form fadeOut
var userInput;
var classInput;
var raceInput;
$('input[type=submit]').click(function(){
$('#newPlayer').fadeOut(500);
userInput = $('input[name="user"]').val();
classInput = $('input[name="class"]:checked').val();
raceInput = $('input[name="race"]:checked').val();
});
Maybe this helps. First, you will have to put values on those inputs
<form id="newPlayer">
Username:<br>
<input type="text" name="user"/><br>
Please Choose a Class: <br>
<input value="archer" type="radio" name="class"/>Archer
<input value="mage" type="radio" name="class"/>Mage
<input value="warrior" type="radio" name="class"/>Warrior
<br>
Please Choose a Race: <br>
<input value="orc" type="radio" name="race"/>Orc
<input value="elf" type="radio" name="race"/>Elf
<input value="human" type="radio" name="race"/>Human
<input value="worg" type="radio" name="race"/>Worg
<br>
<input type="submit" value="Submit">
</form>
Then, using jQuery, a simple .val() will do the job:
var class_val = $('input[name="class"]:checked').val();
var race = $('input[name="race"]:checked').val();
var user = $('input[name="user"]').val();
After that, you just need to put in localStorage
localStorage.setItem('class', class_val);
localStorage.setItem('race', race);
localStorage.setItem('user', user);
To access those values in the future, you do that
var stored_class = localStorage.getItem('class');
var stored_race = localStorage.getItem('race');
var stored_user = localStorage.getItem('user');
To make things happens on submit, you add an submit event to the form, like that:
$('form').on('submit', function() {
// Get values
var class_val = $('input[name="class"]:checked').val();
...
// Store values
localStorage.setItem('class', class_val);
...
// Avoid form submit
return false;
});
Hope it helps :)
I think I would use localStorage.
For example:
//Make sure to set the selection variable to a object that contains the selections made by the user.
function save() {
//This will save the current settings as an object to the localStorage.
localStorage.selections = JSON.stringify(selections) ;
}
function load() {
if (!localStorage.selections) {
alart("No saves found.") ;
return false ;
}
selections = JSON.parse(localStorage.selections) ;
}
Read more about localStorage here.

Javascript adding values to radio buttons to input price

Im trying to create a javascript block inside of a webpage im working on. I havent done javascript since highschool and it doesnt seem to want to come back to me :(
In this block of code i want to have 4 sets of radio buttons, each time a selection is picked,
a price will be inputed to a variable for each radio group. i.e
var firstPrice = $25
var secondPrice = $56
var thirdPrice = $80
var fourthPrice = $90
then after each radio group has one selection there will be a function attached to the submit button that adds up each price to display the final amount inside of a hidden field
var totalPrice = (firstPrice + secondPrice + thirdPrice + fourthPrice)
My question is, how do i attach a number value to a radio button within a group, same name but id is different in each group. Then do i just create a function that adds all the price groups up and then set the submit button to onClick = totalPrice();
Here is an example of one set of radio buttons:
<label>
<input type="radio" name="model" value="radio" id="item_0" />
item 1</label>
<br />
<label>
<input type="radio" name="model" value="radio" id="item_1" />
item2</label>
<br />
<label>
<input type="radio" name="model" value="radio" id="item_2" />
item3</label>
<br />
<label>
<input type="radio" name="model" value="radio" id="item_3" />
Item4</label>
<br />
<label>
<input type="radio" name="model" value="radio" id="item_4" />
item5</label>
</form>
then my script looks something like:
function finalPrice90{
var selectionFirst = document.modelGroup.value;
var selectionSecond = document.secondGroup.value;
var selectionThird = document.thirdGroup.value;
var selectionFourth = document.fourthGroup.Value;
var totalPrice = (selectionFirst + selectionSecond + selectionThird + selectionFourth);
}
Try this fiddle
http://jsfiddle.net/tariqulazam/ZLQXB/
Set the value attribute of your radio inputs to the price each radio button should represent.
When it's time to calculate, simply loop through each group and get the value attribute if the checked radio.
Because the value attribute is a string representation of a number, you'll want to convert it back to a number before doing any math (but that's a simple parseInt or parseFloat).
Here's a working fiddle using pure JavaScript: http://jsfiddle.net/XxZwm/
A library like jQuery or Prototype (or MooTools, script.aculo.us, etc) may make this easier in the long run, depending on how much DOM manipulation code you don't want to re-invent a wheel for.
Your requirements seem pretty simple, here's an example that should answer most questions. There is a single click listener on the form so whenever there is a click on a form control, the price will be updated.
<script type="text/javascript">
//function updatePrice(el) {
function updatePrice(event) {
var el = event.target || event.srcElement;
var form = el.form;
if (!form) return;
var control, controls = form.elements;
var totalPrice = 0;
var radios;
for (var i=0, iLen=controls.length; i<iLen; i++) {
control = controls[i];
if ((control.type == 'radio' || control.type == 'checkbox') && control.checked) {
totalPrice += Number(control.value);
}
// Deal with other types of controls if necessary
}
form.totalPrice.value = '$' + totalPrice;
}
</script>
<form>
<fieldset><legend>Model 1</legend>
<input type="radio" name="model1" value="25">$25<br>
<input type="radio" name="model1" value="35">$35<br>
<input type="radio" name="model1" value="45">$45<br>
<input type="radio" name="model1" value="55">$55<br>
</fieldset>
<fieldset><legend>Model 2</legend>
<input type="radio" name="model2" value="1">$1<br>
<input type="radio" name="model2" value="2">$2<br>
<input type="radio" name="model2" value="3">$3<br>
<input type="radio" name="model2" value="4">$4<br>
<fieldset><legend>Include shipping?</legend>
<span>$5</span><input type="checkbox" value="5" name="shipping"><br>
</fieldset>
<input name="totalPrice" readonly><br>
<input type="reset" value="Clear form">
</form>
You could put a single listener on the form for click events and update the price automatically, in that case you can get rid of the update button.

Categories

Resources