Check and summed if two or more checkbox is checked - javascript

I have an 4 input checkbox tag, and 1 div tag to display a price if one checkbox is checked
<input type="checkbox" value="None" id="check1" />
<input type="checkbox" value="None" id="check2" />
<input type="checkbox" value="None" id="check3" />
<input type="checkbox" value="None" id="check4" />
<div id="price"></div>
What i want to do if only 1 random checkbox is checked it will display number 1,800 on div#price, but if 2 checkbox is checked it will summed become 3,600 and so on until 4 checkbox. But i really confused how to do that using jQuery. Any idea?

Use :checkbox selector to assign change event on all thre type = checkbox elements, one can add [value="None"] while selecing checkbox elements to be more specific.
Use :checkbox:checked selector to select the checked checkboxes.
var val = 1800;
$(':checkbox[value="None"]').on('change', function() {
var len = $(':checkbox:checked').length;
$('#price').text(len * val);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<input type="checkbox" value="None" id="check1" />
<input type="checkbox" value="None" id="check2" />
<input type="checkbox" value="None" id="check3" />
<input type="checkbox" value="None" id="check4" />
<div id="price"></div>

HTML
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<input type="checkbox" value="100" id="check1" />
<input type="checkbox" value="21" id="check2" />
<input type="checkbox" value="22" id="check3" />
<input type="checkbox" value="4" id="check4" />
<div id="price"></div>
JAVASCRIPT
var price=0;
$(':checkbox').on('change', function() {
var len = parseInt(this.value);
if($(this).is(':checked')){
price+=len;
}else{
price-=len;
}
console.log(price)
$('#price').text(price);
});
JSBIN
JSBIN-URL

Related

How to show count of selected checkboxes in a table

Array.prototype.shuffle = function() {
let m = this.length, i;
while (m) {
i = (Math.random() * m--) >>> 0;
[this[m], this[i]] = [this[i], this[m]]
}
return this;
}
$('#select_random').on('click', function() {
if ($(this).prop('checked')) {
let minnum = 3, maxnum = 6
let rand = Math.min(maxnum, Math.floor(Math.random() * ($('.check').length - 1 - minnum)) + minnum)
//create our keys array
let keyArray = [...Array($('.check').length).keys()].shuffle().slice(0, rand)
keyArray.forEach((chk_i, i) => {
if (i < rand) $($('.check').get(chk_i)).prop('checked', true)
})
} else {
$('.check').prop('checked', false);
}
});
const selectedElm = document.getElementById('selected');
function showChecked(){
selectedElm.innerHTML = document.querySelectorAll('input[name=check]:checked').length;
}
document.querySelectorAll("input[name=check]").forEach(i=>{
i.onclick = () => showChecked();
});
Using this script to select random amount of checkboxes in table.
Want to show count number of selected checkboxes count.
Tried some sample not working. Tried this example, not working for me. Tring to get result in div span area like below.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label>Select Random <input type='checkbox' id="select_random"></label>
<div id="result">Total Number of Items Selected = <span id="selected">0</span></div>
<div class='cb'>
<input type="checkbox" name="check[]" class="check"> checkbox <br />
<input type="checkbox" name="check[]" class="check"> checkbox <br />
<input type="checkbox" name="check[]" class="check"> checkbox <br />
<input type="checkbox" name="check[]" class="check"> checkbox <br />
<input type="checkbox" name="check[]" class="check"> checkbox <br />
<input type="checkbox" name="check[]" class="check"> checkbox <br />
<input type="checkbox" name="check[]" class="check"> checkbox <br />
<input type="checkbox" name="check[]" class="check"> checkbox <br />
<input type="checkbox" name="check[]" class="check"> checkbox <br />
<input type="checkbox" name="check[]" class="check"> checkbox <br />
<input type="checkbox" name="check[]" class="check"> checkbox <br />
<input type="checkbox" name="check[]" class="check"> checkbox <br />
<input type="checkbox" name="check[]" class="check"> checkbox <br />
<input type="checkbox" name="check[]" class="check"> checkbox <br />
<input type="checkbox" name="check[]" class="check"> checkbox <br />
Solution
let checked = $(".check:checked");
in your case :
$(".check:checked").length // will return count of checked checkboxes;
i hope it was useful
Here is a code snippet showing how to count checked checkboxes. If I have misunderstood your problem, let me/us know and I will either alter or delete this answer
console.log(document.querySelectorAll("input:checked").length);
1<input type="checkbox" checked/>
2<input type="checkbox" checked/>
3<input type="checkbox"/>
4<input type="checkbox" checked/>
Here is one possible solution
const checkboxContainer = document.querySelector('.cb');
function showChecked(){
selectedElm.innerHTML = checkboxContainer.querySelectorAll('input[type=checkbox]:checked').length;
}
You want to limit the search to a parent container tag and also filter out by input type.

Push and pop data from array based on checkbox check and uncheck value using jQuery

var listvalues = []
$('.check').on('change', function() {
var val = this.checked ? this.value : '';
listvalues.push(val)
$('#show').html(listvalues);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js" type="text/javascript"></script>
<input type="checkbox" class="check" value="1" />1
<input type="checkbox" class="check" value="2" />2
<input type="checkbox" class="check" value="3" />3
<input type="checkbox" class="check" value="4" />4
<div id="show"> </div>
I have a code which should push and pop checkbox value based on checkbox check and uncheck, for example if I check and checkbox it should show the value in a div and if I unselect the checkbox the value should disappear from div, and it should not allow anyone to append duplicate data.
But what I did appends even if it is duplicate it appends the data. Can anyone help me on this?
and i wanted to create separate div for each checkbox
Instead of push & pop value from array, you can get all checked values with listvalues = $('.check:checked').toArray().map(x => x.value); and display it.
$('.check:checked') will only return .check which are checked. Then .toArray() will convert jquery object into array & get use .map(x => x.value) to fetch only value from checked elements.
var listvalues = []
$('.check').on('change', function() {
listvalues = $('.check:checked').toArray().map(x => x.value).join(', ');
$('#show').html(listvalues);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js" type="text/javascript"></script>
<input type="checkbox" class="check" value="1" />1
<input type="checkbox" class="check" value="2" />2
<input type="checkbox" class="check" value="3" />3
<input type="checkbox" class="check" value="4" />4
<div id="show"> </div>
To remove you can use filter to exclude the unchecked item. I'm not sure what you want to achieve with different divs, please explain.
var listvalues = []
$('.check').on('change', function() {
if(this.checked){
listvalues.push(this.value);
}
else {
listvalues = listvalues.filter(item => item != this.value);
}
$('#show').html(listvalues.sort());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js" type="text/javascript"></script>
<input type="checkbox" class="check" value="1" />1
<input type="checkbox" class="check" value="2" />2
<input type="checkbox" class="check" value="3" />3
<input type="checkbox" class="check" value="4" />4
<div id="show"> </div>

checkbox name i need in text field

<input type="checkbox" name="checkbox" id="checkbox1" value="10" /> Value 1
<input type="checkbox" name="checkbox" id="checkbox2" value="20" /> value 2
<input type="checkbox" name="checkbox" id="checkbox3" value="30" /> value 3
<input type="checkbox" name="checkbox" id="checkbox4" value="40" /> value 4
<input type="checkbox" name="checkbox" id="checkbox5" value="50" /> value 5
Ect, etc. I want the add value of selected checkboxes in a text field and all selected checkbox value in a diffrent diffrent checkboxes.
Using this code for the adding of checkboxes but dont know how to get the name of the check box as well as dynamic. For example value 1 , value 2, value 3 in a textbox in front of checkbox in a hidden form.
Code of adding is given below.
$(document).ready(function () {
$("#textfield2").val( $("#textfield").val());
$('.priceAdded input[type="checkbox"]').on("change", function () {
var priceAdded = $("#textfield").val();
$('.priceAdded input[type="checkbox"]').each(function () {
if ($(this).is(":checked")) {
priceAdded = parseFloat(priceAdded) + parseFloat($(this).val());
}
$("#textfield2").val(priceAdded);
});
});
return false;
});
If you're wanting to get the id of the checkboxes and a total of the selected values
http://jsfiddle.net/hb0hhbk4/1/
HTML
<input type="checkbox" name="checkbox" id="checkbox1" value="10" class='sum' />Value 1
<input type="checkbox" name="checkbox" id="checkbox2" value="20" class='sum' />value 2
<input type="checkbox" name="checkbox" id="checkbox3" value="30" class='sum' />value 3
<input type="checkbox" name="checkbox" id="checkbox4" value="40" class='sum' />value 4
<input type="checkbox" name="checkbox" id="checkbox5" value="50" class='sum' />value 5
<input id='textfield1' type='text' />
<input id='textfield2' type='text' />
JS
$("input[type='checkbox'].sum").on('click', function () {
var total = 0;
var ids = [];
$("input[type='checkbox'].sum:checked").each(function () {
var value = parseInt($(this).val());
total += value;
ids.push($(this).attr('id'));
});
ids = ids.join(" ", ids);
$('#textfield1').val(ids);
$('#textfield2').val(total);
});
If you're looking for the LABEL near the checkbox, you need to do something like this
<span><input type="checkbox" name="checkbox" id="checkbox1" value="10" /> Value 1</span>
<span><input type="checkbox" name="checkbox" id="checkbox2" value="20" /> value 2</span>
<span><input type="checkbox" name="checkbox" id="checkbox3" value="30" /> value 3</span>
<span><input type="checkbox" name="checkbox" id="checkbox4" value="40" /> value 4</span>
<span><input type="checkbox" name="checkbox" id="checkbox5" value="50" /> value 5</span>
And inside the each function you can access the label with
$( this ).closest( "span" ).text();
Using that layout, you probably won't be able to, because there's no way of isolating "value 1", for example, from the rest of the code (it isn't the content of an element, or an attribute of anything.
You could put the "Value 1/2/3/4" text in something like a span and then you can use the adjacent selector in Jquery. for example::
<input type="checkbox" name="checkbox" id="checkbox1" value="10" /> <span>Value 1</span>
Then use
$(this).next().text();
To get the contents of the span directly after the checkbox that's just been clicked.

Check-boxes with Radio-buttons quality

I need check-boxes list that has one quality of radio-buttons:
That you can check only one of them.
I don't want to use radio-buttons, becouse I need other qualities of check-boxes, like that you can un-check it by additional click.
Is there any simple way to do it?
I can use javascript, including knockout and jquery libraries.
DEMO
$(function() {
$(':checkbox').on('change',function() {
$(':checkbox[name=' + this.name + ']:checked').not(this).prop('checked',false);
});
});
HTML:
<fieldset>
<legend>Group1</legend>
<input type="checkbox" class="radio" value="1" name="fooby[1][]" />
<input type="checkbox" class="radio" value="1" name="fooby[1][]" />
<input type="checkbox" class="radio" value="1" name="fooby[1][]" />
</fieldset>
<fieldset>
<legend>Group2</legend>
<input type="checkbox" class="radio" value="1" name="fooby[2][]" />
<input type="checkbox" class="radio" value="1" name="fooby[2][]" />
<input type="checkbox" class="radio" value="1" name="fooby[2][]" />
</fieldset>
Checkbox Group exactly like a radio button group
jsfiddle:
Checkbox Group
Javascript:
$("input:checkbox").click(function(){
var group = "input:checkbox[name='"+$(this).attr("name")+"']";
$(group).attr("checked",false);
$(this).attr("checked",true);
});
Checkbox Group you can remove all checked.
jsfiddle:
Checkbox Group(can remove all checked)
Javascript:
$("input:checkbox").change(function(){
var group = "input:checkbox[name='"+$(this).attr("name")+"']";
$(group).not(this).prop("checked",false);
$(this).prop("checked",!this.checked);
});

Wrapping groups of input elements with jQuery

I have following code:
<input type="checkbox" name="field_1" value="on" /> Checkbox field_1
<input type="checkbox" name="field_1" value="off" /> Checkbox field_1
<input type="checkbox" name="field_2" value="on" /> Checkbox field_2
<input type="checkbox" name="field_2" value="off" /> Checkbox field_2
I need to wrap those elements with jQuery. It should look something like this:
<div>
<input type="checkbox" name="field_1" value="on" /> Checkbox field_1
<input type="checkbox" name="field_1" value="off" /> Checkbox field_1
</div>
<div>
<input type="checkbox" name="field_2" value="on" /> Checkbox field_2
<input type="checkbox" name="field_2" value="off" /> Checkbox field_2
</div>
I tried $("input[name=field_1]".wrappAll("<div></div>") but this will create a wrapper around the input elements but will not include the "Checkbox field_1...."
I suggest that you should modify existing code to become something like this:
<label><input type="checkbox" name="field_1" value="on" /> Checkbox field_1</label>
<label><input type="checkbox" name="field_1" value="off" /> Checkbox field_1</label>
<label><input type="checkbox" name="field_2" value="on" /> Checkbox field_2</label>
<label><input type="checkbox" name="field_2" value="off" /> Checkbox field_2</label>
This will not only simplify your jQuery code (for jQuery is very good working with tag nodes and not that good working with text nodes) but also will improve accessibility since labels after checkboxes will become clickable.
Then in jQuery:
$('input[name="field_1"]').parent().wrapAll('<div/>')
Try this:
function wrapFieldSet(fields) {
var wrapper = $('<div class="wrapper"></div>');
fields.first().before(wrapper);
fields.each(function() {
var text = $(this.nextSibling);
wrapper.append($(this)).append(text);
});
}
wrapFieldSet($('input[name="field_1"]'));
I was going to suggest wrapping Checkbox field_1 etc in a label, adding classes to each one and using this wrap example jQuery API to accomplish your goal
i.e.
<input id="foo1" class="bar" type="checkbox" name="field_1" value="on" />
<label class="bar" for="foo1">Checkbox field_1</label>
<input id="foo2" class="bar" type="checkbox" name="field_1" value="off" />
<label class="bar" for="foo2">Checkbox field_1</label>
Then use
$('.bar').wrap('<div class="something" />');
Then do the second section with a different class
Try this
var $div = $("<div />"), next, $this;
$("input[name=field_1]:first").before($div);
$("input[name=field_1]").each(function(){
$this = $(this);
next = $this.next();
$div.append($this);
$div.append(next)
});
$div = $("<div />");
it should work :
$('input[name=field_1]').wrapAll('<div />');
Click Here

Categories

Resources