multiple checkbox actions - javascript

I wanted to make multiple checkboxes and every time I check one of them the value of the first input reduce by a number for example when we select checkbox1 the number in input reduces by 10 and when we select checkbox2 it reduces by 20 and when we select both of them it reduces by 30.
I have handled the first checkbox though.
<html lang="en">
<head>
</head>
<body>
<input type="number" id="input">
<input type="checkbox" onclick="one()" id="checkboxId">
<input type="checkbox" onclick="" id="checkboxId2">
<p id="par">hello</p>
<script>
function one () {
var check = document.getElementById("checkboxId");
if (check.checked) {
let input = document.getElementById("input").value;
y = input - 10;
document.getElementById("par").innerHTML = y;
} else {
document.getElementById("par").innerHTML=document.getElementById("input").value;
}
}
</script>
</body>
</html>

You can try using data-* attribute. Also, you can get the value only from the checked check boxes, sum them and deduct that from the input value.
Try the following way:
function one () {
var total = Array.from(document.querySelectorAll(':checked'))
.map(el => el.getAttribute('data-value'))
.reduce((a,c) => a+ Number(c), 0);
document.getElementById("par").textContent = Number(document.getElementById("input").value) - total;
}
<input type="number" id="input">
<input type="checkbox" onclick="one()" data-value="10" id="checkboxId">
<input type="checkbox" onclick="one()" data-value="20" id="checkboxId2">
<p id="par">hello</p>

Related

Multiplying a text input by selected radio button

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>

Calculate total price by checking checkboxes

I have made a script that gets a number based on checked checkboxes, then there is a input where users can input a number which then gets calculated with my total numbers that I got from checkboxes. So my issue is that the total number doesn't gets updated when I uncheck/check checkbox again, and I need it to automatically update.
// Total Price Calculator
function calc() {
var tots = 0;
$(".checks:checked").each(function() {
var price = $(this).attr("data-price");
tots += parseFloat(price);
});
$("#no-text").keyup(function() {
var value = parseFloat($(this).val());
$('#tots').text(value*tots.toFixed(2));
});
}
$(function() {
$(document).on("change", ".checks", calc);
calc();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" class="checks" data-price="10">
<input type="checkbox" class="checks" data-price="10">
<input type="checkbox" class="checks" data-price="10">
<input type="number" id="no-text" placeholder="10">
<span id="tots">0.00</span>
So I need all of this to be done automatically, if I check 1st and 2nd checkbox and set input to number 5 it will calculate the price, then if I uncheck one checkbox it should update the price automatically according to already inputted number without need to update it again.
Thanks!
You can have multiple elements in one event handler, so include #no-text so that they'll both fire the calc event when either the checkbox or the input is updated
Then move $('#tots').text((number * tots).toFixed(2)) out of the old event listener, and add another variable to fetch the value of the input element
// Total Price Calculator
function calc() {
// Get value from input
let number = parseFloat($('#no-text').val() || 0);
let tots = 0;
// Add Checkbox values
$(".checks:checked").each(function() {
tots += $(this).data("price");
});
// Update with new Number
$('#tots').text((number * tots).toFixed(2));
}
$(function() {
$(document).on('change', '.checks, #no-text', calc);
calc();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" class="checks" data-price="10">
<input type="checkbox" class="checks" data-price="10">
<input type="checkbox" class="checks" data-price="10">
<input type="number" class="duration-input" id="no-text" placeholder="10">
<span id="tots">0.00</span>

addEventListener to multiple checkboxes

Below, I have a simple form that has 4 checkboxes acting as seats. What I am trying to do is when a visitor chooses, say, seat checkboxes with IDs A2 and A4, I want those IDs and their total value to be shown instantly after clicking inside a paragraph with which have a name called id="demo". When a button [Reserve Now] has been clicked, the total value should be assigned to a variable called $TotalCost.
How can I accomplish this? Here's my code:
<!DOCTYPE html>
<html>
<body>
<h2>Please choose a seat to book</h2>
<form action="/action_page.php" method="post">
<input type="checkbox" name="vehicle" id="A1" value="$100">$100<br>
<input type="checkbox" name="vehicle" id="A2" value="$65"> $65<br>
<input type="checkbox" name="vehicle" id="A3" value="$55"> $55<br>
<input type="checkbox" name="vehicle" id="A4" value="$50"> $50<br>
<p id="demo">
Selected Seat(s)
<br>
<br>
Total: USD <input type="submit" value="Reserve Now">
</form>
</p>
<script>
document.getElementById("A1").addEventListener("click", displayCheck);
function displayCheck() {
document.getElementById("demo").innerHTML = ;
}
</script>
</body>
</html>
Here's one approach to setting up event listeners on checkboxes. I used document.querySelectorAll("input[type='checkbox']"); to fetch all of the checkbox elements from the DOM and a loop to add a listener to each checkbox. A selections object can keep track of which items have been checked. When a checkbox is clicked on, the item values are added to the object by key. When the checkbox is off, the item is deleted from the object. Whenever an action happens, the DOM is updated with all relevant information based on the contents of selections.
This example is just a quick sketch to give you the idea. You'll need another event listener for your submit button to handle sending the form data to your PHP script. I'll leave that as an exercise.
Note that the HTML you've provided is invalid because nesting is broken. A HTML validator can be helpful for fixing these sort of problems.
var selections = {};
var checkboxElems = document.querySelectorAll("input[type='checkbox']");
var totalElem = document.getElementById("seats-total");
var seatsElem = document.getElementById("selected-seats");
for (var i = 0; i < checkboxElems.length; i++) {
checkboxElems[i].addEventListener("click", displayCheck);
}
function displayCheck(e) {
if (e.target.checked) {
selections[e.target.id] = {
name: e.target.name,
value: e.target.value
};
}
else {
delete selections[e.target.id];
}
var result = [];
var total = 0;
for (var key in selections) {
var listItem = "<li>" + selections[key].name + " " +
selections[key].value + "</li>";
result.push(listItem);
total += parseInt(selections[key].value.substring(1));
}
totalElem.innerText = total;
seatsElem.innerHTML = result.join("");
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>...</title>
</head>
<body>
<h2>Please choose a seat to book</h2>
<form action="/action_page.php" method="post">
<input type="checkbox" name="vehicle" id="A1" value="$100">$100<br>
<input type="checkbox" name="vehicle" id="A2" value="$65"> $65<br>
<input type="checkbox" name="vehicle" id="A3" value="$55"> $55<br>
<input type="checkbox" name="vehicle" id="A4" value="$50"> $50<br>
<p>Selected Seat(s)</p>
<!-- container for displaying selected seats -->
<ul id="selected-seats"></ul>
<div>
Total: $<span id="seats-total">0</span> USD
<input type="submit" value="Reserve Now">
</div>
</form>
</body>
</html>
Often, you'll want to generate the elements dynamically and add event listeners. Here's a toy example:
for (let i = 0; i < 1000; i++) {
const checkbox = document.createElement("input");
document.body.appendChild(checkbox);
checkbox.type = "checkbox";
checkbox.style.margin = 0;
checkbox.addEventListener("mouseover", e => {
e.target.checked = !e.target.checked;
});
checkbox.addEventListener("mouseout", e =>
setTimeout(() => {
e.target.checked = !e.target.checked;
}, 1000)
);
}
See also event delegation which lets you add a single listener on many child elements.
Here is a starter... About the math addition.
Since your question was tag with jQuery, It's a jQuery way.
Notice that the form will only send something like {vehicle:['on','','on','on']}... Which is way far from anyone would want to send to the server. But that is another question.
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<h2>Please choose a seat to book</h2>
<form action="/action_page.php" method="post">
<input type="checkbox" name="vehicle" id="A1" value="100">$100<br>
<input type="checkbox" name="vehicle" id="A2" value="65"> $65<br>
<input type="checkbox" name="vehicle" id="A3" value="55"> $55<br>
<input type="checkbox" name="vehicle" id="A4" value="50"> $50<br>
Selected Seat(s): <span id="seats"></span>
<br>
<br>
Total: $<span id="demo">0.00</span> USD <input type="submit" value="Reserve Now">
</form>
<script>
$(document).ready(function(){
var total=0;
var seats=[];
$("form input").on("click",function(){
var id=$(this).attr("id");
if($(this).is(":checked")){
total+=parseInt($(this).val());
seats.push(id);
}else{
total-=parseInt($(this).val());
seats.splice(seats.indexOf(id),1);
}
$("#demo").text(total.toFixed(2));
$("#seats").html(seats.sort().join(","));
});
});
</script>
</body>
</html>

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>

Categories

Resources