How to get an added value from multiple checkboxes in javascript/jquery? - javascript

I have multiple checkboxes added with a button. I want to assign a value of 150 for each checkbox that is checked. Maybe my logic is wrong, but i cant get it working. Ideas?
function getValues() {
var cost = 0;
var isChecked = $('.isLab').prop('checked');
$('.isLab').each(function () {
if (isChecked == true) {
cost = 150
}
});
alert(cost);
}

$('button').click(getValues);
function getValues() {
alert( $('.isLab:checked').length * 150 );
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="checkbox" class="isLab"/> Item 1<br/>
<input type="checkbox" class="isLab"/> Item 2<br/>
<input type="checkbox" class="isLab"/> Item 3<br/>
<button>Get values</button>

Comments inline...
function getValues() {
var cost = 0;
$('.isLab').each(function (index, element) {
if (element.checked == true) { // reference current checkbox
cost += 150; // ADD to it!
}
});
alert(cost);
}

Related

Removing value from array according to index using splice()

I have 4 checkboxes. I add values of them to an array on check. It looks like this.
Here are the four checkboxes I have.
<input type="checkbox" value="degree">
<input type="checkbox" value="pgd">
<input type="checkbox" value="hnd">
<input type="checkbox" value="advdip">
Once I check all four of them, the array becomes,
["degree", "pgd", "hnd", "advdip"]
When I uncheck a checkbox, I need to remove the value of it from the array according to its correct index number. I used splice() but it always removes the first index which is degree. I need to remove the value from the array according to its index number no matter which checkbox I unselect. Hope someone helps. Below is the code. Thanks in advance!
<input type="checkbox" value="degree">
<input type="checkbox" value="pgd">
<input type="checkbox" value="hnd">
<input type="checkbox" value="advdip">
<script>
function getLevels() {
// get reference to container div of checkboxes
var con = document.getElementById('course-levels');
// get reference to input elements in course-levels container
var inp = document.getElementsByTagName('input');
// create array to hold checkbox values
var selectedValues = [];
// collect each input value on click
for (var i = 0; i < inp.length; i++) {
// if input is checkbox
if (inp[i].type === 'checkbox') {
// on each checkbox click
inp[i].onclick = function() {
if ($(this).prop("checked") == true) {
selectedValues.push(this.value);
console.log(selectedValues);
}
else if ($(this).prop("checked") == false) {
// get index number
var index = $(this).index();
selectedValues.splice(index, 1);
console.log(selectedValues);
}
}
}
}
}
getLevels();
</script>
You used the wrong way to find index in your code. If you used element index, it will avoid real index in your array and gives the wrong output. Check below code, it may be work for you requirement.
<input type="checkbox" value="degree">
<input type="checkbox" value="pgd">
<input type="checkbox" value="hnd">
<input type="checkbox" value="advdip">
<script src="https://code.jquery.com/jquery-3.5.0.min.js" integrity="sha256-xNzN2a4ltkB44Mc/Jz3pT4iU1cmeR0FkXs4pru/JxaQ=" crossorigin="anonymous"></script>
<script>
function getLevels() {
// get reference to container div of checkboxes
var con = document.getElementById('course-levels');
// get reference to input elements in course-levels container
var inp = document.getElementsByTagName('input');
// create array to hold checkbox values
var selectedValues = [];
// collect each input value on click
for (var i = 0; i < inp.length; i++) {
// if input is checkbox
if (inp[i].type === 'checkbox') {
// on each checkbox click
inp[i].onclick = function() {
if ($(this).prop("checked") == true) {
selectedValues.push(this.value);
console.log(selectedValues);
}
else if ($(this).prop("checked") == false) {
// get index number
var index = selectedValues.indexOf(this.value);
selectedValues.splice(index, 1);
console.log(selectedValues);
}
}
}
}
}
getLevels();
</script>
Add change handler to the inputs and use jQuery map to get the values of the checked inputs.
var levels
$('#checkArray input').on('change', function () {
levels = $('#checkArray input:checked').map(function () {
return this.value
}).get()
console.log(levels)
}).eq(0).change()
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<fieldset id="checkArray">
<input type="checkbox" value="degree" checked>
<input type="checkbox" value="pgd">
<input type="checkbox" value="hnd">
<input type="checkbox" value="advdip">
</fieldset>
my approach was to add an event handler that reads all checked values when any of those inputs is clicked and empty the array before loging the response. no need to add any dependencies with this one
Hope this is what you are looking for
function getLevels() {
let checkboxContainer = document.getElementById("checkboxContainer");
let inputs = checkboxContainer.querySelectorAll("input");
let checked = [];
inputs.forEach( (input) => {
checked = [];
input.addEventListener( 'click', () => {
checked = [];
inputs.forEach( (e) => {
e.checked ? checked.push(e.value) : null;
})
console.log(checked);
});
});
}
getLevels();
<div id="checkboxContainer">
<input type="checkbox" value="degree" >
<input type="checkbox" value="pgd">
<input type="checkbox" value="hnd">
<input type="checkbox" value="advdip">
</div>
I don't know if this is what you need, to show an array of the selected values, if you want you can call the function that calculates on the check.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
<fieldset id="checkArray">
<input type="checkbox" value="degree" checked>
<input type="checkbox" value="pgd">
<input type="checkbox" value="hnd">
<input type="checkbox" value="advdip">
</fieldset>
<button onclick="getLevels()">getLevels</button>
<script>
function getLevels() {
var levels = [];
$.each($("input:checked"), function() {
levels.push(($(this).val()));
});
console.log(levels);
}
getLevels();
</script>

unselecting radio input selection

In a part of my application where i check for duplicate radio input selection and revert if its already selected to early selection.
Here is my html code ..
<input type="radio" name="A" checked="checked" onclick="return check();" />
<input type="radio" name="A" onclick="return check();" />
<br />
<input type="radio" name="B" onclick="return check();" />
<input type="radio" name="B" checked="checked" onclick="return check();" />
Here is the javascript code
function check() {
//logic to check for duplicate selection
alert('Its already selected');
return false;
}
And here is the demo
The above code works fine. The issue is when the input isn't initially checked. In such condition the radio input selection doesn't revert to unchecked.
NOTE: when in checked state, returning false shows and alert and sets the check box to initial checked state. But when initially in non checked state this doesn't work.
In DOM ready, check if any radio button is checked or not. If any radio button is checked, increase the counter by one. In onclick of the radio button, check if the counter value is 1. if yes, return false, else increase counter by 1.
try this code,
html
<input type="radio" name="A" checked="checked" />
<input type="radio" name="A" />
<br />
<input type="radio" name="B" />
<input type="radio" name="B" />
JS
var counterA = 0;
var counterB = 0;
$(document).ready(function () {
if ($("input:radio[name=A]").is(":checked") == true) counterA++;
if ($("input:radio[name='B']").is(":checked") == true) counterB++;
});
$('input:radio[name=A]').click(function () {
if (counterA == 1) {
alert('already checked');
return false;
} else {
counterA++;
}
});
$('input:radio[name=B]').click(function () {
if (counterB == 1) {
alert('already checked');
return false;
} else {
counterB++;
}
});
SEE THIS DEMO
iJay wants to ask several questions and privides the same answers for each question. Each answer can only be choosen once. If a user clicks the same answer the second time a error-message should be shown.
// get all elements
var elements = document.querySelectorAll('input[type="radio"]');
/**
* check if radio with own name is already selected
* if so return false
*/
function check(){
var selected_name = this.name,
selected_value = this.value,
is_valid = true;
// compare with all other elements
for(var j = 0; j < len; j++) {
var el = elements[j];
// does the elemenet have the same name AND is already selected?
if(el.name != selected_name && el.value == selected_value && el.checked){
// if so, selection is not valid anymore
alert('Oups..! You can not select this answer a second time :( Choose another one!')
// check current group for previous selection
is_valid = false;
break;
}
};
return is_valid;
}
/**
* bind your elements to the check-routine
*/
for(var i = 0, len = elements.length; i < len; i++) {
elements[i].onmousedown = check;
}
Here is a DEMO
Use $yourRadio.prop('checked', false); to uncheck the specific radio.
Use like this:
function check() {
//logic to check for duplicate selection
var checked = true ? false : true;
$(this).prop('checked', checked);
return false;
}
1) add class attribute to same type of checkbox elements(which are having same name)
ex: class = "partyA"
2)
var sourceIdsArr = new Array();
function check() {
$('.partyA').each(function() {
var sourceId = $(this).val();
if(sourceIdsArr.indexOf(sourceId) != -1){
sourceIdsArr.push(sourceId );
}
else{
alert('Its already selected');
return false;
}
});
}
Here is your code..
function check() {
//logic to check for duplicate selection
var selectflag=0;
var radiovalue=document.getElementsByName("B");
for(var i=0;i<radiovalue.length;i++)
{
// alert(radiovalue[i].checked);
if(radiovalue[i].checked==true)
{
selectflag=1;
break;
}
}
if(selectflag==1)
{
alert('Its already selected');
return false;
}
return true;
}
Trigger your event on MouseDown. It will work fine.
I think this is something you are looking for :
<html>
<head>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
</head>
<body>
<input type="radio" name="A" checked="checked" onclick="return check(this);"/>
<input type="radio" name="A" onclick="return check(this);"/>
<script>
$( document ).ready(function() {
this.currentradio = $("input[name='A']:checked")[0];
});
function check(t) {
var newradio= $("input[name='A']:checked")[0];
if (newradio===document.currentradio){
alert('already selected');
return false
}else{
document.currentradio = $("input[name='A']:checked")[0];
}
}
</script>
</body>
<html>

How to get value of different checkboxes and calculate value of those checked checkboxes and show in the input field?

I have a little problem with getiing the value of diffrent checkboxes when it is checked. Here is my code
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.js"></script>
<script>
$(document).ready(function(){
$('input[type="checkbox"]').bind('click',function()
{
var waterdm = $('#waterdm').val();
$("#price").val(waterdm);
});
});
</script>
<p><input type="checkbox" id="waterdm" name="waterdm" value="10" />Water Damage</p>
<p><input type="checkbox" id="screendm" name="screendm" value="20" />Screen Damage</p>
<p><input type="checkbox" id="Chargerdm" name="Chargerdm" value="30" />Charger Damage</p>
<p><input type="checkbox" id="hdphdm" name="hdphdm" value="10" />Headphone Damage</p>
<p>
Calculated Price: <input type="text" name="price" id="price" />
</p>
What I want is whenever user check in checkboxes I need to get those value and show the sum of each checkbox value which is checked in to another input box. It Means I need to sum those value of each checkbox
is checked.And when user unchecked any of the checkboxes then that value should subtracted from the that total. I don't have enough experience in jquery. Please help me.
You would need to iterate over the cheboxes. And change event makes more sense when you are talking in terms of checkboxes..
Use on to attach events instead of bind
$(document).ready(function () {
// cache the inputs and bind the events
var $inputs = $('input[type="checkbox"]')
$inputs.on('change', function () {
var sum = 0;
$inputs.each(function() {
// iterate and add it to sum only if checked
if(this.checked)
sum += parseInt(this.value);
});
$("#price").val(sum);
});
});
Check Fiddle
$(document).ready(function () {
var waterdm = 0;
$('input[type="checkbox"]').bind('click', function (e) {
if (this.checked) {
waterdm += eval(this.value);
} else {
waterdm -= eval(this.value);
}
$("#price").val(waterdm);
});
});
Demo here
Try this
$(document).ready(function(){
var waterdm=0;
$('input[type="checkbox"]').on('click',function()
{
waterdm = waterdm+parseInt($(this).val());
$("#price").val(waterdm);
});
});
Demo
You can use following code
$(document).ready(function(){
$('input[type="checkbox"]').click(function()
{
var val = 0;
$('input[type="checkbox"]:checked').each(function(){
val+=parseInt($(this).val());
});
$("#price").val(val);
});
});
Demo
If you want to sum all checked checkboxes try something like this:
$('input[type="checkbox"]').bind('click',function()
{
var sum = 0;
$('input[type="checkbox"]:checked').each(function(){
var val = parseInt($(this).val());
sum += val;
});
$("#price").val(sum);
});

Stop checking checkboxes after a number of checkboxes have been checked in jQuery or JavaScript

I want to stop the user to check another checkbox after a certain number of checkboxes have been checked already. i.e. After 3 checkboxes are checked, the user cannot check anymore and a message says 'You're not allowed to choose more than 3 boxes.'
I'm almost there but the last checkbox is still being checked and I don't want that, I want it to be unchecked with the message appearing.
How do I do that:
var productList = $('.prod-list'),
checkBox = productList.find('input[type="checkbox"]'),
compareList = $('.compare-list ul');
productList.delegate('input[type="checkbox"]', 'click', function () {
var thisElem = $(this),
thisData = thisElem.data('compare'),
thisImg = thisElem.closest('li').find('img'),
thisImgSrc = thisImg.attr('src'),
thisImgAlt = thisImg.attr('alt');
if (thisElem.is(':checked')) {
if ($('input:checked').length < 4) {
compareList.append('<li data-comparing="' + thisData + '"><img src="' + thisImgSrc + '" alt="'+ thisImgAlt +'" /><li>');
} else {
$('input:checked').eq(2).attr('checked', false);
alert('You\'re not allowed to choose more than 3 boxes');
}
} else {
var compareListItem = compareList.find('li');
for (var i = 0, max = compareListItem.length; i < max; i++) {
var thisCompItem = $(compareListItem[i]),
comparingData = thisCompItem.data('comparing');
if (thisData === comparingData) {
thisCompItem.remove();
}
}
}
});
I might have misunderstood the question... see my comment.
Too prevent the selection, you can call event.preventDefault() and define the handler with the event parameter.
$('input[type="checkbox"]').click(function(event) {
if (this.checked && $('input:checked').length > 3) {
event.preventDefault();
alert('You\'re not allowed to choose more than 3 boxes');
}
});
DEMO
Alternatively, set this.checked to false. This will even prevent the browser from rendering the checkmark.
DEMO
one single jquery function for multiple forms
<form>
<input type="checkbox" name="seg"><br>
<input type="checkbox" name="seg" ><br>
<input type="checkbox" name="seg"><br>
<input type="checkbox" name="seg"><br>
</form>
<br><br><br><br><br>
<form>
<input type="checkbox" name="seg1"><br>
<input type="checkbox" name="seg1" ><br>
<input type="checkbox" name="seg1"><br>
<input type="checkbox" name="seg1"><br>
</form>
$('input[type="checkbox"]').click(function(event) {
if ($("input[name= "+ this.name +"]:checked").length > 3) {
event.preventDefault();
alert('You\'re not allowed to choose more than 3 boxes');
}
});

Javascript checkbox onChange

I have a checkbox in a form and I'd like it to work according to following scenario:
if someone checks it, the value of a textfield (totalCost) should be set to 10.
then, if I go back and uncheck it, a function calculate() sets the value of totalCost according to other parameters in the form.
So basically, I need the part where, when I check the checkbox I do one thing and when I uncheck it, I do another.
Pure javascript:
const checkbox = document.getElementById('myCheckbox')
checkbox.addEventListener('change', (event) => {
if (event.currentTarget.checked) {
alert('checked');
} else {
alert('not checked');
}
})
My Checkbox: <input id="myCheckbox" type="checkbox" />
function calc()
{
if (document.getElementById('xxx').checked)
{
document.getElementById('totalCost').value = 10;
} else {
calculate();
}
}
HTML
<input type="checkbox" id="xxx" name="xxx" onclick="calc();"/>
If you are using jQuery.. then I can suggest the following:
NOTE: I made some assumption here
$('#my_checkbox').click(function(){
if($(this).is(':checked')){
$('input[name="totalCost"]').val(10);
} else {
calculate();
}
});
Use an onclick event, because every click on a checkbox actually changes it.
The following solution makes use of jquery. Let's assume you have a checkbox with id of checkboxId.
const checkbox = $("#checkboxId");
checkbox.change(function(event) {
var checkbox = event.target;
if (checkbox.checked) {
//Checkbox has been checked
} else {
//Checkbox has been unchecked
}
});
HTML:
<input type="checkbox" onchange="handleChange(event)">
JS:
function handleChange(e) {
const {checked} = e.target;
}
Reference the checkbox by it's id and not with the #
Assign the function to the onclick attribute rather than using the change attribute
var checkbox = $("save_" + fieldName);
checkbox.onclick = function(event) {
var checkbox = event.target;
if (checkbox.checked) {
//Checkbox has been checked
} else {
//Checkbox has been unchecked
}
};
Javascript
// on toggle method
// to check status of checkbox
function onToggle() {
// check if checkbox is checked
if (document.querySelector('#my-checkbox').checked) {
// if checked
console.log('checked');
} else {
// if unchecked
console.log('unchecked');
}
}
HTML
<input id="my-checkbox" type="checkbox" onclick="onToggle()">
try
totalCost.value = checkbox.checked ? 10 : calculate();
function change(checkbox) {
totalCost.value = checkbox.checked ? 10 : calculate();
}
function calculate() {
return other.value*2;
}
input { display: block}
Checkbox: <input type="checkbox" onclick="change(this)"/>
Total cost: <input id="totalCost" type="number" value=5 />
Other: <input id="other" type="number" value=7 />
I know this seems like noob answer but I'm putting it here so that it can help others in the future.
Suppose you are building a table with a foreach loop. And at the same time adding checkboxes at the end.
<!-- Begin Loop-->
<tr>
<td><?=$criteria?></td>
<td><?=$indicator?></td>
<td><?=$target?></td>
<td>
<div class="form-check">
<input type="checkbox" class="form-check-input" name="active" value="<?=$id?>" <?=$status?'checked':''?>>
<!-- mark as 'checked' if checkbox was selected on a previous save -->
</div>
</td>
</tr>
<!-- End of Loop -->
You place a button below the table with a hidden input:
<form method="post" action="/goalobj-review" id="goalobj">
<!-- we retrieve saved checkboxes & concatenate them into a string separated by commas.i.e. $saved_data = "1,2,3"; -->
<input type="hidden" name="result" id="selected" value="<?= $saved_data ?>>
<button type="submit" class="btn btn-info" form="goalobj">Submit Changes</button>
</form>
You can write your script like so:
<script type="text/javascript">
var checkboxes = document.getElementsByClassName('form-check-input');
var i;
var tid = setInterval(function () {
if (document.readyState !== "complete") {
return;
}
clearInterval(tid);
for(i=0;i<checkboxes.length;i++){
checkboxes[i].addEventListener('click',checkBoxValue);
}
},100);
function checkBoxValue(event) {
var selected = document.querySelector("input[id=selected]");
var result = 0;
if(this.checked) {
if(selected.value.length > 0) {
result = selected.value + "," + this.value;
document.querySelector("input[id=selected]").value = result;
} else {
result = this.value;
document.querySelector("input[id=selected]").value = result;
}
}
if(! this.checked) {
// trigger if unchecked. if checkbox is marked as 'checked' from a previous saved is deselected, this will also remove its corresponding value from our hidden input.
var compact = selected.value.split(","); // split string into array
var index = compact.indexOf(this.value); // return index of our selected checkbox
compact.splice(index,1); // removes 1 item at specified index
var newValue = compact.join(",") // returns a new string
document.querySelector("input[id=selected]").value = newValue;
}
}
</script>
The ids of your checkboxes will be submitted as a string "1,2" within the result variable. You can then break it up at the controller level however you want.

Categories