Use values of checkbox based on which is checked, in variable - javascript

I would like to make a variable which has the values of 1 or multiple checkboxes, based on which one is selected. This is what I came up with for now:
var checkbox1 = document.getElementById("value1");
var checkbox2 = document.getElementById("value2");
var checkbox3 = document.getElementById("value3");
var showvalue = document.getElementById("show-value");
document.querySelectorAll('input[type=checkbox]')
.forEach(box => box.addEventListener('change', showValue));
function showValue() {
if (checkbox1.checked === true) {
showvalue.value = checkbox1.value;
}
}
<input id="value1" type="checkbox" value="3 maanden"><label for="value1">Value 1</label>
<input id="value2" type="checkbox" value="6 maanden"><label for="value2">Value 2</label>
<input id="value3" type="checkbox" value="Uitgeschreven"><label for="value3">Value 3</label>
<input id="show-value" type="hidden"/>
But I don't know how to iterate through checkboxes and if the specific one is checked, add it to variable showvalue. So what I want for showvalue is something like this (based on which checkbox is checked):
var showvalue = checkbox1.value + ", " + checkbox2.value + ", " + checkbox3.value;
How do I iterate through checkboxes and then if checked = true add that value to showvalue?

For showing I delete the hidden from the showvalue-inputfield and set it to readonly.
For calculating the result I go with foreach through the checkboxes and add if checked to the resultstring the value. The separator , is only set if there is already a partresult. After this at the end just update the value from showvalue.
var checkbox1 = document.getElementById("value1");
var checkbox2 = document.getElementById("value2");
var checkbox3 = document.getElementById("value3");
var showvalue = document.getElementById("show-value");
document.querySelectorAll('input[type=checkbox]')
.forEach(box => box.addEventListener('change', showValue));
function showValue() {
let value = '';
document.querySelectorAll('input[type=checkbox]').forEach(box => {
if (box.checked === true) {
if (value.length) value += ', ';
value += box.value;
}
});
showvalue.value = value;
}
.readonly { background: yellow;}
<input id="value1" type="checkbox" value="3 maanden"><label for="value1">Value 1</label>
<input id="value2" type="checkbox" value="6 maanden"><label for="value2">Value 2</label>
<input id="value3" type="checkbox" value="Uitgeschreven"><label for="value3">Value 3</label>
<input id="show-value" size=40 class="readonly" readonly/>

you can try this:
var showvalue = document.getElementById("show-value");
var checkboxes = document.querySelectorAll('input[type=checkbox]');
checkboxes.forEach(box => box.addEventListener('change', showValue));
function showValue() {
showvalue.value = Array.from(checkboxes).map(e => e.checked ? e.value : null).filter(Boolean).join(", ");
}
<input id="value1" type="checkbox" value="3 maanden"><label for="value1">Value 1</label>
<input id="value2" type="checkbox" value="6 maanden"><label for="value2">Value 2</label>
<input id="value3" type="checkbox" value="Uitgeschreven"><label for="value3">Value 3</label>
<input id="show-value" type="text"/>

Just use querySelector and use name attribute to check for what is checked or not. An example:
let result = [];
const setup = () => {
const entry1 = document.querySelectorAll('[name="entry1"]');
entry1.forEach(input => input.addEventListener('change', onChange));
}
const onChange = () => {
const checkedEntry1 = document.querySelectorAll('[name="entry1"]:checked');
result = [];
checkedEntry1.forEach(input => result.push(input.value));
document.querySelector('#show-value').value = result.join(', ');
}
//load
window.addEventListener('load', setup);
<input id="value1" name="entry1" type="checkbox" value="3 maanden"><label for="value1">Value 1</label>
<input id="value2" name="entry1" type="checkbox" value="6 maanden"><label for="value2">Value 2</label>
<input id="value3" name="entry1" type="checkbox" value="Uitgeschreven"><label for="value3">Value 3</label>
<input id="show-value" type="hidden">

Is it that what you were looking for?
var checkbox1 = document.getElementById("value1");
var checkbox2 = document.getElementById("value2");
var checkbox3 = document.getElementById("value3");
document.querySelectorAll('input[type=checkbox]')
.forEach(box => box.addEventListener('change', showValue));
function showValue() {
if (checkbox1.checked === true) {
var box1 = checkbox1.value;
}else{
var box1 = '';
}
if (checkbox2.checked === true) {
var box2 = checkbox2.value;
}else{
var box2 = '';
}
if (checkbox3.checked === true) {
var box3 = checkbox3.value;
}else{
var box3 = '';
}
document.getElementById("show").value = box1 + ';' + box2 + ';' + box3;
}
<input id="value1" type="checkbox" value="3 maanden"><label for="value1">Value 1</label>
<input id="value2" type="checkbox" value="6 maanden"><label for="value2">Value 2</label>
<input id="value3" type="checkbox" value="Uitgeschreven"><label for="value3">Value 3</label>
<input id="show" class="readonly" readonly/>

document.querySelectorAll('input[type=checkbox]')
.forEach(box => box.addEventListener('input', showValue));
function showValue(event) {
var input = event.target;
var showvalue = document.getElementById('show-value');
showvalue.value += input.value;
// tern if statment
input.checked ? showvalue.type = 'text' : showvalue.type = 'hidden';
// you can used the original if statment
if (input.checked) {
showvalue.type = 'text';
} else {
showvalue.type = 'hidden';
}
}

Related

calculate button question, html and javascript

i just changed my question to show my attempt at it. This is what im trying to do. The XPlevels have a set value, and using that i wanna calculate and display the price
function setprice() {
var val;
var type = document.getElementByName("XP")
if (type[0].checked)
{
var val = 200;
}
else if (type[1].checked)
{
var val = 150;
}
else if (type[2].checked)
{
var val = 100;
}
}
function Calculate() {
var FName = document.getElementById("FName");
var numppl = document.getElementById("numppl");
var Tprice = val * numppl;
window.alert(FName + ", the membership amount is: R " + BasePrice);
<input type="radio" name="XP" value="Novice" onclick="setprice" />Novice
<input type="radio" name="XP" value="Intermediate" onclick="setprice" />Intermediate
<input type="radio" name="XP" value="Expert" onclick="setprice" />Expert
<label for="Members">Number of members</label>
<input id="numppl" type="number" name="Members" size="2" />
<input type="button" value="Calculate fee" onclick="Calculate"/>
You can use onclick event on the Calculate Fee Button to call a JavaScript Function that checks which radio button is selected.
const calculateFee = () => {
let radioButtons = document.querySelectorAll("input");
for(let i=0; i<3; i++){
if(radioButtons[i].checked){
console.log(`Checked Radio Button is : ${radioButtons[i].value}`);
}
}
}
<input type="radio" name="XP" value="Novice" />Novice
<input type="radio" name="XP" value="Intermediate" checked />Intermediate
<input type="radio" name="XP" value="Expert" />Expert
<br />
<label for="Members">Number of members</label>
<input type="number" name="Members" size="2" />
<input type="button" value="Calculate fee" onclick="calculateFee()"/>
This is an edit of your JS code
function setprice() {
var type = document.querySelectorAll('[name="XP"]');
if (type[0].checked) {
var val = 200;
}
else if (type[1].checked) {
var val = 150;
}
else if (type[2].checked) {
var val = 100;
}
return val;
}
function calculate() {
var fName = document.getElementById("FName");
var numppl = document.getElementById("numppl");
var val = setprice();
var tprice = val * numppl.value;
// window.alert(FName + ", the membership amount is: R " + BasePrice);
console.log(tprice);
}
<input type="radio" name="XP" value="Novice" onclick="setprice" />Novice
<input type="radio" name="XP" value="Intermediate" onclick="setprice" />Intermediate
<input type="radio" name="XP" value="Expert" onclick="setprice" />Expert
<label for="Members">Number of members</label>
<input id="numppl" type="number" name="Members" size="2" />
<input type="button" value="Calculate fee" onclick="calculate()" />
This example a more correct approach to what you want
On each radio button, the value is the number (unit price) to be calculated. I have added a data attribute from which to take "Type"
The input named member must be set to a minimum value so that the user cannot set a negative value.
Try this code and if you have any questions I will supplement my answer!
var radio = document.querySelectorAll('.radio');
var number = document.querySelector('.number');
var button = document.querySelector('.button');
var getval;
var datainf;
button.addEventListener('click', function () {
radio.forEach(function (el) {
if (el.checked) {
getval = +el.value;
datainf = el.getAttribute('data');
}
});
var result = getval * number.value;
console.log( 'Quantity: ' + number.value + ' / Type: ' + datainf + ' / The membership amount is: ' + result);
});
<input type="radio" class="radio" name="XP" value="200" data="Novice" />Novice
<input type="radio" class="radio" name="XP" value="150" data="Intermediate" checked />Intermediate
<input type="radio" class="radio" name="XP" value="100" data="Expert" />Expert
<br />
<label for="Members">Number of members</label>
<input type="number" class="number" name="Members" size="2" value="1" min="1" />
<input type="button" class="button" value="Calculate fee" />

How to get a Checkbox Value in JavaScript

I need to get a list of the checkbox values when checked and passed them to an input. However, my value is duplicated when I click checkall first. Please help me. Thanks.
My Code
<input id="listvalue" name="selectedCB">
<input type="checkbox" onclick="toggle(this)" name="checkedAll" id="checkedAll" />
<div class="tycheck">
<input type="checkbox" name="checkAll" value="2" class="checkSingle" />
<input type="checkbox" name="checkAll" value="1" class="checkSingle" />
<input type="checkbox" name="checkAll" value="3" class="checkSingle" />
</div>
$(document).ready(displayCheckbox);
var idsArr = [];
var displayField = $('input[name=selectedCB]');
function toggle(source) {
var checkboxes = document.querySelectorAll('.tycheck input[type="checkbox"]');
for (var i = 0; i < checkboxes.length; i++) {
if (checkboxes[i] != source)
checkboxes[i].checked = source.checked;
idsArr = [];
$('#checkall').find('input[type=checkbox]:checked').each(function () {
idsArr.push(this.value);
});
displayField.val(idsArr);
}
}
function displayCheckbox() {
var checkboxes = $(".tycheck input[type=checkbox]");
function printChecked() {
var checkedIds = [];
idsArr = [];
// for each checked checkbox, add it's id to the array of checked ids
checkboxes.each(function () {
if ($(this).is(':checked')) {
idsArr.push($(this).attr('value'));
console.log(idsArr);
}
else {
var checkboxesallcheck = document.querySelectorAll('input[name="checkedAll"]');
for (var j = 0; j < checkboxesallcheck.length; j++) {
checkboxesallcheck[j].checked = false;
}
}
displayField.val(idsArr);
});
}
$.each(checkboxes, function () {
$(this).change(printChecked);
})
}
How to get a list of the checkbox values when checked and passed them to an input. :(
You can try this:
var idsArr = [];
var displayField = $('input[name=selectedCB]');
var checkboxes = Array.from($(".tycheck input[type=checkbox]"));
function toggle(source) {
var values = checkboxes.map(x => {
x.checked = source.checked;
return source.checked ? x.value : '';
}).join(source.checked ? ',' : '');
displayField.val(values);
}
function printChecked() {
var values = checkboxes.filter(x => x.checked).map(x => x.value);
displayField.val(values);
}
$.each(checkboxes, function () {
$(this).change(printChecked);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<input id="listvalue" name="selectedCB">
<input type="checkbox" onclick="toggle(this)" name="checkedAll" id="checkedAll" />
<div class="tycheck">
<input type="checkbox" name="checkAll" value="2" class="checkSingle" />
<input type="checkbox" name="checkAll" value="1" class="checkSingle" />
<input type="checkbox" name="checkAll" value="3" class="checkSingle" />
</div>
You could do like this
Use any one of the type javascript selector or JQuery selector
Not necessary to use Array or forloops .All function already there in jquery concept .For that we used Jquery.map
For below i have simply create one change function call.checker
Then call that function on checkbox change event in both checkall and normal check event
$(document).ready(function() {
const elem = $('.tycheck input[type=checkbox]'); //select the checkbox elem
elem.on('change', function() {
checker(elem) //get the checked value list
})
$('#checkedAll').on('change', function() {
elem.prop('checked', $(this).is(':checked')) //for select all simply compare with checkall button
checker(elem)
})
})
function checker(elem) {
let res = elem.map((i, item) => {
if ($(item).is(':checked')) {
return $(item).val()
}
}).get()
$('#listvalue').val(res.toString())
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="listvalue" name="selectedCB">
<input type="checkbox" name="checkedAll" id="checkedAll" />
<div class="tycheck">
<input type="checkbox" name="checkAll" value="2" class="checkSingle" />
<input type="checkbox" name="checkAll" value="1" class="checkSingle" />
<input type="checkbox" name="checkAll" value="3" class="checkSingle" />
</div>

Add -remove an option to dropdown menu

I am trying to write to a function. Whn I check a checkbox, the items belongs to that checkbox item comes to dropdown menu, and when I uncheck it, it goes away from the dropdpwn. I can add, but cannot remove when I uncheck the checkbox.Here is my code.
var items = [
"#1001#item1#10.5#10#1#direc1#",
"#1002#item2#20.5#10#2#direc2#",
"#1003#item3#20.5#10#3#director3#",
];
function checkboxChange(ev) {
var count = items.length;
var select = document.getElementById('formsec');
for (var i = 0; i < count; i++){
if (ev.value=="1001" &&ev.checked ) {
var item = items[i];
var currentitem = item.split('#');
if (currentitem[5]=="1" ) {
var opt = document.createElement('option');
opt.value = currentitem[1];
opt.innerHTML = currentitem[2];
select.appendChild(opt);
}
HTML
<td>
Choose the item: </br>
<input type="checkbox" id="category1" name="choice" value="1001" onchange="checkboxChange(this)" />Category1<br />
<input type="checkbox" id="category2" name="choice" value="1002" onchange="checkboxChange(this)" />Category2<br />
<input type="checkbox" id="category3" name="choice" value="1003" onchange="checkboxChange(this)" />Category3<br />
</td>
Working example using querySelector and select.remove().
Only works with Category 1 because OP conditions:
if (ev.value == "1001")
if (currentitem[5] == "1")
var items = [
"#1001#item1#10.5#10#1#direc1#",
"#1002#item2#20.5#10#2#direc2#",
"#1003#item3#20.5#10#3#director3#",
];
function checkboxChange(ev) {
var count = items.length;
var select = document.getElementById('formsec');
for (var i = 0; i < count; i++) {
if (ev.value == "1001") {
var item = items[i];
var currentitem = item.split('#');
if (currentitem[5] == "1") {
if (ev.checked) {
var opt = document.createElement('option');
opt.value = currentitem[1];
opt.innerHTML = currentitem[2];
select.appendChild(opt);
} else {
var opt = document.querySelector("option[value='" + currentitem[1] + "']");
select.remove(opt);
}
}
}
}
}
<select id="formsec"></select>
<td>
Choose the item: <br />
<input type="checkbox" id="category1" name="choice" value="1001" onchange="checkboxChange(this)" /><label for="category1">Category1</label><br />
<input type="checkbox" id="category2" name="choice" value="1002" onchange="checkboxChange(this)" /><label for="category2">Category2</label><br />
<input type="checkbox" id="category3" name="choice" value="1003" onchange="checkboxChange(this)" /><label for="category3">Category3</label><br />
</td>
This may help you. I implement this without an array. Use an associated label with each checkbox.
function checkboxChange(ev) {
$('#formsec').html("");
$('input[type=checkbox]').each(function () {
var chk = (this.checked ? $(this).val() : "");
if(chk){
$('#formsec').append('<option value="'+chk+'" selected="selected">'+$("label[for='"+this.id+"']").text()+'</option>');
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
Choose the item:<br />
<input type="checkbox" id="category1" name="choice" value="1001" onchange="checkboxChange(this)" />
<label for="category1">Category1</label>
<br />
<input type="checkbox" id="category2" name="choice" value="1002" onchange="checkboxChange(this)" />
<label for="category2">Category2</label>
<br />
<input type="checkbox" id="category3" name="choice" value="1003" onchange="checkboxChange(this)" />
<label for="category3">Category3</label>
</div>
<select id="formsec"></select>
Instead setting an onChange handler in html I would recommend binding an input-handler and rebuild the selectbox each time, even on document load like
var items = [
"#1001#item1#10.5#10#1#direc1#",
"#1002#item2#20.5#10#2#direc2#",
"#1003#item3#20.5#10#3#director3#"
];
function rebuild() {
var select = document.getElementById('formsec');
select.innerHTML = "";
[].forEach.call(document.querySelectorAll("input[type=checkbox]"), (el) => {
if (el.checked) {
var opt = document.createElement('option');
var currentitem = items.find(
(item) => item.startsWith("#" + el.value)
).split("#");
opt.value = currentitem[1];
opt.innerHTML = currentitem[2];
select.appendChild(opt);
}
});
}
[].forEach.call(document.querySelectorAll("input[type=checkbox]"), (el) => {
el.addEventListener("input", rebuild);
});
rebuild();
Choose the item:<br>
<input type="checkbox" id="category1" name="choice" value="1001">Category1<br>
<input type="checkbox" id="category2" name="choice" value="1002" checked>Category2<br>
<input type="checkbox" id="category3" name="choice" value="1003">Category3<br>
<select id="formsec"></select>

How set checked checkbox if it's value is in array

I have inputs:
<div id="my">
<input type="checkbox" value="1" name="names[]">
<input type="checkbox" value="2" name="names[]">
<input type="checkbox" value="3" name="names[]">
<input type="checkbox" value="4" name="names[]">
</div>
And my javascript:
initValues=[1,2,3];
$('#my').find(':checkbox[name="names[]"]').each(function () {
$(this).prop("checked", ($.inArray($(this).val(), initValues)));
});
And now all my checkboxes are checked. How must I change my code to set checked for ckeckboxes which values are in initValues array?
$.inArray returns the index, not boolean. Also, parseInt your value because its considered as string when you pick it up.
initValues=[1,2,3];
$('#my').find(':checkbox[name="names[]"]').each(function () {
$(this).prop("checked", $.inArray(parseInt($(this).val()), initValues) == -1 ? false : true );
});
let initValues = [1, 2, 3];
$('#my').find(':checkbox[name="names[]"]').each(function() {
if (initValues.some(v => v == $(this).val())) {
$(this).prop('checked', true);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="my">
<input type="checkbox" value="1" name="names[]">
<input type="checkbox" value="2" name="names[]">
<input type="checkbox" value="3" name="names[]">
<input type="checkbox" value="4" name="names[]">
</div>
You need to turn the value back into a number so it compares with the array value.
$.inArray(+$(this).val(), initValues))
Revised Example:
initValues=[1,2,3];
$('#my').find(':checkbox[name="names[]"]').each(function () {
$(this).prop("checked", ($.inArray(+$(this).val(), initValues)) != -1);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="my">
<input type="checkbox" value="1" name="names[]">
<input type="checkbox" value="2" name="names[]">
<input type="checkbox" value="3" name="names[]">
<input type="checkbox" value="4" name="names[]">
</div>
function printChecked(isChecked, value) {
const newProjectStages = projectstage.filter((p) => p !== value);
if (isChecked) {
newProjectStages.push(value);
}
Setprojectstage(newProjectStages);
var items = document.getElementsByName("tr");
var selectedItems = [];
for (var i = 0; i < items.length; i++) {
if (items[i].type == "checkbox" && items[i].checked == true)
selectedItems.push(items[i].value);
}
console.log("selected val", selectedItems);
Setselectedprostages(selectedItems);
}

Manipulating label with checkboxes

Scenario:
Three unchecked check-boxes, each with different id and value.
An empty paragraph (or label) with id = par.
[CB1] has value 1.
[CB2] has value 2.
[CB3] has value 3.
Now, when I click cb1 -> 'par' gets and prints the value of cb1.
Clicking on cb3, 'par' gets the value of cb1+cb3.
Clicking cb1, 'par' subtracts the value of cb1 and so on.. I think you get the point.
How can I achieve this with only HTML and JavaScript (without jQuery).
<input type="checkbox" id="1" value="1" />
<input type="checkbox" id="2" value="2" />
<input type="checkbox" id="3" value="3" />
<p id="par"></p>
This will do it: jsfiddle example (updated to remove alert)
HTML:
<input type="checkbox" id="1" value="1" onclick='checkClicked(event)'/>
<input type="checkbox" id="2" value="2" onclick='checkClicked(event)'/>
<input type="checkbox" id="3" value="3" onclick='checkClicked(event)'/>
<p id="par"></p>
JavaScript:
function checkClicked(element)
{
var targetElement = element.target;
var newVal = targetElement.value;
if( !targetElement.checked )
{
newVal *= -1;
}
var currentVal = document.getElementById('par').innerHTML;
if( currentVal )
{
newVal = parseInt(currentVal) + parseInt(newVal);
}
document.getElementById('par').innerHTML = newVal;
}
<label>
<input type="checkbox" id="check1" value="check1" onchange="alterP(this);"/>check1
</label>
<label>
<input type="checkbox" id="check2" value="check2" onchange="alterP(this);"/>check2
</label>
<label>
<input type="checkbox" id="check3" value="check3" onchange="alterP(this);"/>check3
</label>
<p id="par"></p>
js Code
function alterP(obj) {
var par = document.getElementById('par');
var txt = (obj.checked) ? obj.value : "";
par.innerHTML = txt;
}
<script>
document.getElementById("1").addEventListener("click", processCheck);
document.getElementById("2").addEventListener("click", processCheck);
document.getElementById("3").addEventListener("click", processCheck);
function processCheck() {
var theParagraph = document.getElementById("par");
var currentValue = 0;
if (!isNaN(parseInt(theParagraph.textContent))) {
currentValue = parseInt(theParagraph.textContent)
}
if (this.checked) {
theParagraph.textContent = currentValue + parseInt(this.value);
}
else {
theParagraph.textContent = currentValue - parseInt(this.value);
}
}
</script>

Categories

Resources