Javascript: How to get selected checkbox items in a table - javascript

I have a checkbox, where I am loading its inputs from a web service. I'm developing a function which filters the selected items and puts them in a table.
My checkbox looks like this:
<label class="checkbox" data-match-for="filtre-competences">
<input id="checkbox_competence" name="missionPlace" value="" type="checkbox" data-match-forcontent="id-competence">
<span class="check"></span>
<span class="checkbox-title" data-match-forcontent="titre-competence"></span>
<span>(<span data-match-forcontent="nb-mission"></span>)</span>
</label>
I want to filter the selected elements in a table and of course deselect items which may bed deselected dynamically.
My function looks like this:
selectCompetences:function () {
var checkbox = document.querySelector('#checkbox_competence');
var arr = new Array();
checkbox.addEventListener('click',function () {
if () {
//selected : add to table
arr.push(checkbox.getAttribute("value"))
}
else {
// deselected: remove from table
}
})
}
I need to complete this function. Any suggestions?

var values = new Array();
$.each($("input[name='case[]']:checked").closest("td").siblings("td"),
function () {
values.push($(this).text());
});
alert("val---" + values.join(", "));

function togglecheckboxes(master,group){
var cbarray = document.getElementsByName(group);
for(var i = 0; i < cbarray.length; i++){
cbarray[i].checked = master.checked;
}
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<input type="checkbox" id="cbgroup1_master" onchange="togglecheckboxes(this,'cbg1[]')"> Toggle All
<br><br>
<input type="checkbox" id="cb1_1" class="cbgroup1" name="cbg1[]" value="1"> Item 1<br>
<input type="checkbox" id="cb1_2" class="cbgroup1" name="cbg1[]" value="2"> Item 2<br>
<input type="checkbox" id="cb1_3" class="cbgroup1" name="cbg1[]" value="3"> Item 3<br>
<input type="checkbox" id="cb1_4" class="cbgroup1" name="cbg1[]" value="4"> Item 4<br>
</body>
</html>

Related

Need help on Checkbox onclick jquery

trying to learn jquery and made a simple checkbox with a function where you can make all the options read-only checking on "none of the above" button.
<html>
<body>
<form id="diagnosedForm">
<div>
<input type="checkbox" value="1"/>1
<br/>
<input type="checkbox" value="2"/>2
<br/>
<input type="checkbox" value="3"/>3
<br/>
</form><br/>
<input type="checkbox" value="" onclick="enableDisableAll(this);"/>None of the above
<script src="script.js">
</script>
</body>
</html>
function enableDisableAll(e) {
var own = e;
var form = document.getElementById("diagnosedForm");
var elements = form.elements;
for (var i = 0 ; i < elements.length ; i++) {
if(own !== elements[i] ){
if(own.checked == true){
elements[i].disabled = true;
elements[i].checked = false;
}else{
elements[i].disabled = false;
}
}
}
}
this will be the output
and the last checkbox will make it read-only
I want the same result but not putting onclick on the html file, instead using jquery to work it out.
You can assign an id to "none of the above" checkbox and then in your script.js you can do something like this:
// script.js
// Run enableDisableAll() on toggle click
$('#toggle').click(enableDisableAll)
function enableDisableAll() {
// Find all input elements inside "diagnosedForm"
const elements = $('#diagnosedForm input')
// Map thru inputs and toggle enable/disable state
elements.map((_, el) => {
$(el).prop('checked', false) // Reset checkboxes
$(el).prop('disabled', (i, v) => !v)
})
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
<body>
<form id="diagnosedForm">
<div>
<input type="checkbox" value="1" />1
<br/>
<input type="checkbox" value="2" />2
<br/>
<input type="checkbox" value="3" />3
<br/>
</div>
</form>
<br/>
<input id="toggle" type="checkbox" value="" /> None of the above
</body>
</html>

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 select all checkbox using jquery or javascript? [duplicate]

This question already has answers here:
How to select all checkboxes with jQuery?
(15 answers)
Closed 8 years ago.
I have multiple checkboxes , there is a checkbox with select all name, now i want that when some tick
the select all checkbox, then all the checkbox must be selected. I think this will be in jquery.
any tutorial link or codes with hints would be appreciated.the code snip is under...
<input type="checkbox" value="">Select All<br/>
<input type="checkbox" value="">A<br/>
<input type="checkbox" value="">B<br/>
<input type="checkbox" value="">C<br/>
<input type="checkbox" value="">D<br/>
<input type="checkbox" value="">E<br/>
<input type="checkbox" value="">F<br/>
<input type="checkbox" value="">G<br/>
<input type="checkbox" value="">H<br/>
This should check all checkboxes when you check the "Select All" one, and also uncheck all checkboxes when you uncheck it.
$("#selectAll").click(function () {
$(":checkbox").not(this).prop("checked", $(this).is(":checked"));
});
If you don't want the uncheck behavior:
$("#selectAll").click(function () {
if ($(this).is(":checked")) {
$(":checkbox").not(this).prop("checked", true);
}
});
But of course, you must identify it. Do it by adding the id="selectAll" attribute (or any other id you wish, just make sure you change the JavaScript code as well):
<input type="checkbox" value="" id="selectAll">Select All<br/>
<input type="checkbox" value="">A<br/>
<input type="checkbox" value="">B<br/>
<input type="checkbox" value="">C<br/>
<input type="checkbox" value="">D<br/>
<input type="checkbox" value="">E<br/>
<input type="checkbox" value="">F<br/>
<input type="checkbox" value="">G<br/>
<input type="checkbox" value="">H<br/>
<input type="checkbox" id="exp" />Tick All Checkbox<br/>
<input type="checkbox" value="demo1" class="subchkbox"/>No 1<br/>
<input type="checkbox" value="demo2" class="subchkbox"/>No 2<br/>
<input type="checkbox" value="demo3" class="subchkbox"/>No 3<br/>
<input type="checkbox" value="demo4" class="subchkbox"/>No 4<br/>
<input type="checkbox" value="demo5" class="subchkbox"/>No 5<br/>
<sctipt type="text/javascript">
/*Include the jquery library 1.9.1*/
$(document).ready(function() {
$('#exp').click(function(event) {
if(this.checked) {
$('.subchkbox').each(function() {
this.checked = true;
});
}else{
$('.subchkbox').each(function() {
this.checked = false;
});
}
});
});
[the fiddle is here][1]
Using jQuery :
$("input[type=checkbox]").prop({ checked : true })
JSFiddle
Using pure JavaScript :
var inputs = document.querySelectorAll('input[type=checkbox]')
Object.keys(inputs).forEach(function(i){
inputs[i].checked = true
})
JSFiddle
$("checkboxContainer").find("input[type='checkbox']").each(function() {
$(this).prop("checked", true);
});
I think using .find() is faster when selecting multiple elements.
If you want to do this in plain JS, it's also pretty simple.
You just have to loop through all of the inputs and set checked to true (or false), which isn't very efficient.
document.getElementById("all").addEventListener("change", function() {
if (this.checked) {
var boxes = document.getElementsByTagName("input");
for (var i = 0; i < boxes.length; i++) {
if (boxes[i].type === "checkbox") {
boxes[i].checked = true;
}
}
} else {
var boxes = document.getElementsByTagName("input");
for (var i = 0; i < boxes.length; i++) {
if (boxes[i].type === "checkbox") {
boxes[i].checked = false;
}
}
}
});
<input type="checkbox" value="" id="all">Select All
<br/>
<input type="checkbox" value="">A
<br/>
<input type="checkbox" value="">B
<br/>
<input type="checkbox" value="">C
<br/>
<input type="checkbox" value="">D
<br/>
<input type="checkbox" value="">E
<br/>
<input type="checkbox" value="">F
<br/>
<input type="checkbox" value="">G
<br/>
<input type="checkbox" value="">H
<br/>
Derived from the current answer marked as correct, it can all be much simpler:
$(document).ready(function()
{
$('#exp').click(function(event)
{
$('.subchkbox').prop({
checked: $(this).prop('checked')
});
});
});

Check all other checkboxes when one is checked

I have a form and group of checkboxes in it. (These checkboxes are dynamically created but I dont think it is important for this question). The code that generates them looks like this (part of the form):
<div id="ScrollCB">
<input type="checkbox" name="ALL" value="checked" checked="checked">
All (if nothing selected, this is default) <br>
<c:forEach items="${serviceList}" var="service">
<input type="checkbox" name="${service}" value="checked"> ${service} <br>
</c:forEach>
</div>
What I want to do is control, whether the checkbox labeled "ALL" is checked and if yes - check all other checkboxes (and when unchecked, uncheck them all).
I tried doing this with javascript like this (found some tutorial), but it doesnt work (and Im real newbie in javascript, no wonder):
<script type="text/javascript">
$ui.find('#ScrollCB').find('label[for="ALL"]').prev().bind('click',function(){
$(this).parent().siblings().find(':checkbox').attr('checked',this.checked).attr('disabled',this.checked);
}); });
</script>
Could you tell me some simple approach how to get it work? Thanks a lot!
demo
updated_demo
HTML:
<label><input type="checkbox" name="sample" class="selectall"/> Select all</label>
<div id="checkboxlist">
<label><input type="checkbox" name="sample[]"/>checkbox1</label><br />
<label><input type="checkbox" name="sample[]"/>checkbox2</label><br />
<label><input type="checkbox" name="sample[]"/>checkbox3</label><br />
<label><input type="checkbox" name="sample[]"/>checkbox4</label><br />
</div>
JS:
$('.selectall').click(function() {
if ($(this).is(':checked')) {
$('div input').attr('checked', true);
} else {
$('div input').attr('checked', false);
}
});
HTML:
<form>
<label>
<input type="checkbox" id="selectall"/> Select all
</label>
<div id="checkboxlist">
<label><input type="checkbox" name="sample[]"/>checkbox1</label><br />
<label><input type="checkbox" name="sample[]"/>checkbox2</label><br />
<label><input type="checkbox" name="sample[]"/>checkbox3</label><br />
<label><input type="checkbox" name="sample[]"/>checkbox4</label><br />
</div>
</form>
JS:
$('#selectall').click(function() {
$(this.form.elements).filter(':checkbox').prop('checked', this.checked);
});
http://jsfiddle.net/wDnAd/1/
Thanks to #Ashish, I have expanded it slightly to allow the "master" checkbox to be automatically checked or unchecked, if you manually tick all the sub checkboxes.
FIDDLE
HTML
<label><input type="checkbox" name="sample" class="selectall"/>Select all</label>
<div id="checkboxlist">
<label><input type="checkbox" class="justone" name="sample[]"/>checkbox1</label><br/>
<label><input type="checkbox" class="justone" name="sample[]"/>checkbox2</label><br />
<label><input type="checkbox" class="justone" name="sample[]"/>checkbox3</label><br />
<label><input type="checkbox" class="justone" name="sample[]"/>checkbox4</label><br />
</div>
SCRIPT
$('.selectall').click(function() {
if ($(this).is(':checked')) {
$('input:checkbox').prop('checked', true);
} else {
$('input:checkbox').prop('checked', false);
}
});
And now add this to manage the master checkbox as well...
$("input[type='checkbox'].justone").change(function(){
var a = $("input[type='checkbox'].justone");
if(a.length == a.filter(":checked").length){
$('.selectall').prop('checked', true);
}
else {
$('.selectall').prop('checked', false);
}
});
Add extra script according to your checkbox group:
<script language="JavaScript">
function selectAll(source) {
checkboxes = document.getElementsByName('colors[]');
for(var i in checkboxes)
checkboxes[i].checked = source.checked;
}
</script>
HTML Code:
<input type="checkbox" id="selectall" onClick="selectAll(this,'color')" />Select All
<ul>
<li><input type="checkbox" name="colors[]" value="red" />Red</li>
<li><input type="checkbox" name="colors[]" value="blue" />Blue</li>
<li><input type="checkbox" name="colors[]" value="green" />Green</li>
<li><input type="checkbox" name="colors[]" value="black" />Black</li>
</ul>
use this i hope to help you i know that this is a late answer but if any one come here again
$("#all").change(function () {
$("input:checkbox").prop('checked', $(this).prop("checked"));
});
Only in JavaScript with auto check/uncheck functionality of master when any child is checked/unchecked.
function FnCheckAll()
{
var ChildChkBoxes = document.getElementsByName("ChildCheckBox");
for (i = 0; i < ChildChkBoxes.length; i++)
{
ChildChkBoxes[i].checked = document.forms[0].CheckAll.checked;
}
}
function FnCheckChild()
{
if (document.forms[0].ChildCheckBox.length > document.querySelectorAll('input[name="ChildCheckBox"]:checked').length)
document.forms[0].CheckAll.checked = false;
else
document.forms[0].CheckAll.checked = true;
}
Master CheckBox:
<input type="checkbox" name="CheckAll" id="CheckAll" onchange="FnCheckAll()" />
Child CheckBox:
<input type="checkbox" name="ChildCheckBox" id="ChildCheckBox" onchange="FnCheckChild()" value="#employee.Id" />```
You can use jQuery like so:
jQuery
$('[name="ALL"]:checkbox').change(function () {
if($(this).attr("checked")) $('input:checkbox').attr('checked','checked');
else $('input:checkbox').removeAttr('checked');
});
A fiddle.
var selectedIds = [];
function toggle(source) {
checkboxes = document.getElementsByName('ALL');
for ( var i in checkboxes)
checkboxes[i].checked = source.checked;
}
function addSelects() {
var ids = document.getElementsByName('ALL');
for ( var i = 0; i < ids.length; i++) {
if (ids[i].checked == true) {
selectedIds.push(ids[i].value);
}
}
}
In HTML:
Master Check box <input type="checkbox" onClick="toggle(this);">
Other Check boxes <input type="checkbox" name="ALL">
You can use the :first selector to find the first input and bind the change event to it. In my example below I use the :checked state of the first input to define the state of it's siblings. I would also suggest to put the code in the JQuery ready event.
$('document').ready(function(){
$('#ScrollCB input:first').bind('change', function() {
var first = $(this);
first.siblings().attr('checked', first.is(':checked'));
});
});
I am not sure why you would use a label when you have a name on the checkbox. Use that as the selector. Plus your code has no labels in the HTML markup so it will not find anything.
Here is the basic idea
$(document).on("click",'[name="ALL"]',function() {
$(this).siblings().prop("checked",this.checked);
});
if there are other elements that are siblings, than you would beed to filter the siblings
$(document).on("click",'[name="ALL"]',function() {
$(this).siblings(":checkbox").prop("checked",this.checked);
});
jsFiddle

JQuery select label of selected checkboxes

When I click a button I want to get the value from each of the checked check boxes. I really just want to populate an array with all the check boxes that are checked.
I started a simplified example here: http://jsfiddle.net/kralco626/JvAdg/1/
The actual code is more like this:
var dataList = new Array(10);
dataList[0] = "Delete";
dataList[1] = LD_LicenseNumber.val();
dataList[2] = $("#LDOperatingCompanies input:checked").val();
And aspx code:
<div id="LDOperatingCompanies">
<input type="checkbox" value="o1" id="o1" name="LDOperatingCompanies" /><label for="o1">o1</label>
<input value="o2" type="checkbox" id="o2" name="LDOperatingCompanies" /><label for="o2">o2</label>
<input value="o3" value="o1" type="checkbox" id="o3" name="LDOperatingCompanies" /><label for="o3">o3</label>
</div>
Thanks!
here is an update to your fiddle that puts all checked boxes into an array Example
HTML
<div id="LDOperatingCompanies">
<input type="checkbox" id="o1" name="LDOperatingCompanies" /><label for="o1">o1</label>
<input type="checkbox" id="o2" name="LDOperatingCompanies" /><label for="o2">o2</label>
<input type="checkbox" id="o3" name="LDOperatingCompanies" /><label for="o3">o3</label>
</div>
<input type="button" id="btn" value="alert checked boxes" />
JavaScript
var checks = [];
$('#btn').click(function(e) {
$(':checked').each(function(index, item) {
checks.push( item );
});
if(checks.length == 0) alert('nothing checked');
else alert(checks);
});

Categories

Resources