Jquery: How to hold checkbox check / uncheck state in hidden field - javascript

i have a html table which i has many checkboxes. when user click on header checkbox then all child checkbox will be checked and unchecked based on header checkbox checked state.
user can uncheck and check any child checkbox too. i want to store child checkbox value in hidden field separated by comma. when child checkbox is selected then checkbox value will be store in hiiden field but if that checkbox value is in hiiden field then will not be store in hidden field.
when user uncheck anyone then that checkbox value will be removed from hidden field.
I tried this way but not successful. so guide me how to achieve it. my code as follows
<table id="tbl" border="10">
<thead>
<tr>
<td><input type="checkbox" id = "chckHead" /></td>
<td>First Row</td>
<td>Second Row</td>
<td>Third Row</td>
</tr>
</thead>
<tbody>
<tr>
<td>
<input type="checkbox" class = "chcktbl" value="101"/>
</td>
<td>1</td>
<td>1</td>
<td>1</td>
</tr>
<tr>
<td>
<input type="checkbox" class = "chcktbl" value="102"/>
</td>
<td>2</td>
<td>2</td>
<td>2</td>
</tr>
<tr>
<td>
<input type="checkbox" class = "chcktbl" value="103"/>
</td>
<td>3</td>
<td>3</td>
<td>3</td>
</tr>
</tbody>
</table>
<input id="hidden" type="hidden" name="hidden">
$(document).ready(function(){
$('#chckHead').click(function () {
$(".chcktbl").prop('checked', $(this).prop("checked"));
});
$(".chcktbl").change(function() {
var values = [];
$('.chcktbl').each(function (index, obj) {
alert('pop');
if (this.checked === true) {
values.push($(this).val());
}
});
});
alert(values.toString());
});

You forget to assign the checkboxes values to the hidden input and also, you have to do so in the header checkbox event listener.
$(document).ready(function() {
var hidden = $('#hidden');
$('#chckHead').click(function() {
var state = $(this).prop('checked');
if(state === false) {
hidden.val('');
}
var vals = [];
$('.chcktbl').each(function() {
$(this).prop('checked', state);
if(this.checked === true) {
vals.push($(this).val());
}
});
hidden.val(vals.toString());
});
$(".chcktbl").change(function() {
var values = [];
$('.chcktbl').each(function(index, obj) {
if(this.checked === true) {
values.push($(this).val());
}
});
hidden.val(values.toString());
});
});
<table id="tbl" border="10">
<thead>
<tr>
<td><input type="checkbox" id="chckHead" /></td>
<td>First Row</td>
<td>Second Row</td>
<td>Third Row</td>
</tr>
</thead>
<tbody>
<tr>
<td>
<input type="checkbox" class="chcktbl" value="101" />
</td>
<td>1</td>
<td>1</td>
<td>1</td>
</tr>
<tr>
<td>
<input type="checkbox" class="chcktbl" value="102" />
</td>
<td>2</td>
<td>2</td>
<td>2</td>
</tr>
<tr>
<td>
<input type="checkbox" class="chcktbl" value="103" />
</td>
<td>3</td>
<td>3</td>
<td>3</td>
</tr>
</tbody>
</table>
<!--for the demo purpose, I changed the type of the input to 'text' to see the result, don't forget to change to 'hidden' again.-->
<input id="hidden" type="text" name="hidden">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Hope I pushed you further.

You should be able to get all checked checkboxes with this selector:
$('input[type=checkbox]:checked')
Then you can call map to get all the ids and join them
string = $('input[type=checkbox]:checked').map(function(idx,element) {
return element.value;
}).join(',')
Then just listen the onChange event for all checkboxes and set the value for the hidden field.

Related

Inverse table search

I have a table search but I would like to make an inverse search. In my jQuery code how can I exchange .hide() -> .show() and .show() -> .hide() when a <input type="checkbox" checked> is false. And when checkbox is checked undo everything.
<input type="text" placeholder="Search..." id="search_field">
<input type="checkbox" checked>
<table id="myTable" border="1">
<thead>
<tr class="myHead">
<th>XDFFD</th>
<th>DFDDY</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td>3</td>
<td>4</td>
</tr>
<tr>
<td>5</td>
<td>6</td>
</tr>
</tbody>
</table>
$('#search_field').on('keyup', function() {
var value = $(this).val();
var patt = new RegExp(value, "i");
$('#myTable').find('tr').each(function() {
if (!($(this).find('td').text().search(patt) >= 0)) {
$(this).not('.myHead').hide();
}
if (($(this).find('td').text().search(patt) >= 0)) {
$(this).show();
}
});
});
You check if the checkbox is checked or not using is(":checked") this will give true or false so depending on this show or hide trs.
Demo Code :
$('#search_field').on('keyup', function() {
var value = $(this).val();
var patt = new RegExp(value, "i");
var checks = $(".checkbox").is(":checked"); //check if checkbox is checked
console.log(checks)
if (value != "") {
$('#myTable tbody').find('tr').each(function() {
var condition = $(this).find('td').text().search(patt) >= 0
//checked
if (checks) {
//show and hide..
condition ? $(this).show() : $(this).hide()
} else {
condition ? $(this).hide() : $(this).show()
}
});
} else {
$('#myTable tbody > tr').show()
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" placeholder="Search..." id="search_field">
<input type="checkbox" class="checkbox" checked>
<table id="myTable" border="1">
<thead>
<tr class="myHead">
<th>XDFFD</th>
<th>DFDDY</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td>3</td>
<td>4</td>
</tr>
<tr>
<td>5</td>
<td>6</td>
</tr>
</tbody>
</table>
Here is an alternative version of the same using a little jQuery extension to make :contains() case insensitive:
// jQuery extension from https://css-tricks.com/snippets/jquery/make-jquery-contains-case-insensitive/
$.expr[":"].contains = $.expr.createPseudo(function(arg) {
return function( elem ) {return $(elem).text().toUpperCase().indexOf(arg.toUpperCase()) >= 0; };
});
$('input').on('input', function() {
$('#myTable tbody tr').each((i,tr)=>$(tr).toggle
( $('td:contains('+$('#search_field').val()+')',tr).length>0 === $(".checkbox").is(":checked") )
)
}).first().focus();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" placeholder="Search..." id="search_field">
<input type="checkbox" class="checkbox" checked>
<table id="myTable" border="1">
<thead>
<tr class="myHead">
<th>XDFFD</th>
<th>DFDDY</th>
</tr>
</thead>
<tbody>
<tr>
<td>1 one</td>
<td>2 two</td>
</tr>
<tr>
<td>3 Three</td>
<td>4 Four</td>
</tr>
<tr>
<td>5 FIVE</td>
<td>6 SIX</td>
</tr>
</tbody>
</table>
The ===comparison of two booleans is in fact something like an XOR condition between the two expressions. The result will be true if both or none of the expressions
$('td:contains('+$('#search_field').val()+')',tr).length>0
and
$(".checkbox").is(":checked")
are true. And this will be used directly in the .toggle() method to show or hide the current <tr>.

Shilft select multiple checkboxes in a table

I found a solution to select a single range of checkboxes in table created by JsGrid.
$(document).on('click', '[type = checkbox]' , function(e) {
if (e.shiftKey) {
var first = $("#jsGrid input[type='checkbox']:checked").first().parent().parent().index(),
last = $("#jsGrid input[type='checkbox']:checked").last().parent().parent().index();
for (var i = first; i < last; i++) {
$("#jsGrid").find("tbody tr index").eq(i).children().first().find("input[type='checkbox']").prop("checked", true);
$("#jsGrid .jsgrid-grid-body tbody tr").eq(i).find("input[type='checkbox']").prop("checked", true)
}
}
});
The problem with this solution is that is only allows for a single range of checkboxes.
To add multiple ranges, I can set the bottom of the range to the current row index with
last = $(this).parent().parent().index();
Now I would like to find the row index of the row with next row above that has a selected checkbox.
I would think it should be a variant of the code below.
first = $(this).prevUntil(':checkbox', 'checked').parent().parent().index(); // -1
I can't get this to work.
Or this
first = $(this).parent().parent().prevUntil(':checkbox', 'checked').index(); // -1
HTML
<tbody>
<tr class="jsgrid-row">
<td>1</td>
<td><input type="checkbox" rel="898"></td>
<td>02/27/2019</td>
<td>19122-37</td>
<td>SMITH</td>
</tr>
<tr class="jsgrid-alt-row">
<td>1</td>
<td><input type="checkbox" rel="898"></td>
<td>02/27/2019</td>
<td>19122-37</td>
<td>SMITH</td>
</tr>
<tr class="jsgrid-row">
<td>1</td>
<td><input type="checkbox" rel="898"></td>
<td>02/27/2019</td>
<td>19122-37</td>
<td>SMITH</td>
</tr>
<tr class="jsgrid-alt-row">
<td>1</td>
<td><input type="checkbox" rel="898"></td>
<td>02/27/2019</td>
<td>19122-37</td>
<td>SMITH</td>
</tr>
</tbody>
Thanks!
[1] What I understand is: When checked the last checkbox get the nearest previous row which has checked checkbox
$('input[type="checkbox"]:last').on('change' , function(){
if(this.checked){
var ThisRowIndex = $(this).closest('tr').index();
$($('table tr:lt('+ (ThisRowIndex) +')').get().reverse()).filter(function(){
return $(this).find('input[type="checkbox"]:checked').length;
}).each(function(){
console.log('This Nearst Row Index: '+ $(this).index() + ' Has checked checkbox');
return false;
});
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tbody>
<tr class="jsgrid-row">
<td>1</td>
<td><input type="checkbox" value="100" rel="898"/></td>
<td>02/27/2019</td>
<td>19122-37</td>
<td>SMITH</td>
</tr>
<tr class="jsgrid-alt-row">
<td>1</td>
<td><input type="checkbox" rel="898"/></td>
<td>02/27/2019</td>
<td>19122-37</td>
<td>SMITH</td>
</tr>
<tr class="jsgrid-row">
<td>1</td>
<td><input type="checkbox" rel="898"/></td>
<td>02/27/2019</td>
<td>19122-37</td>
<td>SMITH</td>
</tr>
<tr class="jsgrid-alt-row">
<td>1</td>
<td><input type="checkbox" rel="898"></td>
<td>02/27/2019</td>
<td>19122-37</td>
<td>SMITH</td>
</tr>
</tbody>
</table>
Explanation:- with checkbox use change event.
if(this.checked){ // if this checkbox checked
var ThisRowIndex = $(this).closest('tr').index(); // get the closest ow index when this checkbox checked
$('table tr:lt('+ (ThisRowIndex) +')').filter(function(){ // use `lt()` to select the previous rows then filter them to check if there is a checked checkbox in each one or not
return $(this).find('input[type="checkbox"]:checked').length; //check if there is a checked checkbox in each one or not
}).each(function(){ // loop through the rows which has checked checkbox
console.log('This Row With Index: '+ $(this).index() + ' Has checked checkbox'); // print the index of each row
});
}
For reverse you can use $($('table tr:lt('+ (ThisRowIndex) +')').get().reverse()) .. see updated snippet
:last for the last element
return false; in .each() break the loop
Note With the above piece of code you can do a lot of things
.. Just understand the idea of it and it will be very helpful for
you
[2] And with prevUntil() to get the indexes of the rows between index checked checkbox and the shift-select checkbox
$('input[type="checkbox"]:last').on('change' , function(){
if(this.checked){
$(this).closest('tr').prevUntil('tr:has(input[type="checkbox"]:checked)').each(function(){
console.log($(this).index());
});
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tbody>
<tr class="jsgrid-row">
<td>1</td>
<td><input type="checkbox" value="100" rel="898"/></td>
<td>02/27/2019</td>
<td>19122-37</td>
<td>SMITH</td>
</tr>
<tr class="jsgrid-alt-row">
<td>1</td>
<td><input type="checkbox" rel="898"/></td>
<td>02/27/2019</td>
<td>19122-37</td>
<td>SMITH</td>
</tr>
<tr class="jsgrid-row">
<td>1</td>
<td><input type="checkbox" rel="898"/></td>
<td>02/27/2019</td>
<td>19122-37</td>
<td>SMITH</td>
</tr>
<tr class="jsgrid-alt-row">
<td>1</td>
<td><input type="checkbox" rel="898"></td>
<td>02/27/2019</td>
<td>19122-37</td>
<td>SMITH</td>
</tr>
</tbody>
</table>

Copy Internal Table value to External table on checkbox click

<!DOCTYPE html>
<html>
<body>
<!--External table-->
<table border="1px">
<tr>
<td>
//price and quantity fields
<input type="text" name="price" label="Price" id="Pri">
<input type="text" name="quantity" label="Quantity" id="Qty">
</td>
<td>
<!--internal table-->
<table border="1px">
<tr>
<th>Price</th>
<th>Quantity</th>
<th>Action</th>
</tr>
<tr>
<td>1</td>
<td>2</td>
<td><input type="checkbox" id="checx"/></td>
</tr>
<tr>
<td>11</td>
<td>22</td>
<td><input type="checkbox" id="checx"/></td>
</tr>
<tr>
<td>111</td>
<td>222</td>
<td><input type="checkbox" id="checx"/></td>
</tr>
<tr>
<td>10</td>
<td>20</td>
<td><input type="checkbox" /></td>
</tr>
</table>
</td>
</tr>
</table>
//Javascript
<script type="text/javascript">
checkboxes = document.getElementById("checx").getElementsByTagName("input");
for (var i = 0; i < checkboxes.length; i++) {
var checkbox = checkboxes[i];
checkbox.onclick = function() {
var currentRow = this.parentNode.parentNode;
var secondColumn = currentRow.getElementsByTagName("td")[1];
var FirstColumn = currentRow.getElementsByTagName("td")[0];
alert("My text is: " + secondColumn.textContent +" "+ FirstColumn.textContent);
};
}
document.getElementById("Pri").value=secondColumn.textContent;
document.getElementById("Qty").value=FirstColumn.textContent;
</script>
//I have a dynamic table on the above pattern.I want in such a way that when I click on the checkbox on the internal table it should copy the values and should show on the input boxes on the corresponding row on the external table.
</body>
</html>
I have a dynamic table on the above pattern.I want in such a way that when I click on the checkbox on the internal table it should copy the values and should show on the input boxes on the corresponding row on the external table.
Thanks for your help in advance
the main issue that checkboxes ids has to be unique per element so you have to depend on class name rather than ids of checkboxes
in addition to the following code
document.getElementById("Pri").value=secondColumn.textContent;
document.getElementById("Qty").value=FirstColumn.textContent;
Has to be inside the event handler
<!DOCTYPE html>
<html>
<body>
<!--External table-->
<table id="parentTable" border="1px">
<tr>
<td>
//price and quantity fields
<input type="text" name="price" label="Price" id="Pri">
<input type="text" name="quantity" label="Quantity" id="Qty">
</td>
<td>
<!--internal table-->
<table border="1px">
<tr>
<th>Price</th>
<th>Quantity</th>
<th>Action</th>
</tr>
<tr>
<td>1</td>
<td>2</td>
<td><input type="checkbox" id="checx1" class="checx"/></td>
</tr>
<tr>
<td>11</td>
<td>22</td>
<td><input type="checkbox" id="checx2" class="checx"/></td>
</tr>
<tr>
<td>111</td>
<td>222</td>
<td><input type="checkbox" id="checx3" class="checx"/></td>
</tr>
<tr>
<td>10</td>
<td>20</td>
<td><input type="checkbox" id="checx4" class="checx" /></td>
</tr>
</table>
</td>
</tr>
</table>
//Javascript
<script type="text/javascript">
checkboxes = document.getElementsByClassName("checx");
for (var i = 0; i < checkboxes.length; i++) {
var checkbox = checkboxes[i];
checkbox.onclick = function() {
var currentRow = this.parentNode.parentNode;
var secondColumn = currentRow.getElementsByTagName("td")[1];
var FirstColumn = currentRow.getElementsByTagName("td")[0];
alert("My text is: " + secondColumn.textContent +" "+FirstColumn.textContent);
document.getElementById("Pri").value=secondColumn.textContent;
document.getElementById("Qty").value=FirstColumn.textContent;
};
}
</script>
</body>
</html>

How to append the checked checkbox to the top of the list in html table?

I'm having some list of HTML check box in the table and its related data. In the list if I have selected a check box that will move to the top of the list.
Below is my code it works in <div> but not in the <table>.
jQuery(function($) {
$('.t1 .group-title').each(function() {
$if(this.checked) {
$item.insertBefore($('.t1 .group-title').first())
} else {
$item.appendTo($item.data('group'))
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="t1">
<thead>
<th></th>
<th>Check</th>
<th>ID</th>
<th>Title</th>
</thead>
<tbody>
<tr>
<td></td>
<td>
<input type="checkbox" id="chk1" name="chk1">
</td>
<td>1</td>
<td>Title 1</td>
</tr>
<tr>
<td>
<input type="checkbox" id="chk2" name="chk2">
</td>
<td>2</td>
<td>Title 2</td>
</tr>
<tr>
<td>
<input type="checkbox" id="chk3" name="chk3">
</td>
<td>3</td>
<td>Title 3</td>
</tr>
<tr>
<td>
<input type="checkbox" id="chk4" name="chk4">
</td>
<td>4</td>
<td>Title 4</td>
</tr>
<tr>
<td>
<input type="checkbox" id="chk5" name="chk5">
</td>
<td>5</td>
<td>Title 5</td>
</tr>
</tbody>
</table>
You should bind the change event to checkbox element. Then based of checked state prepend()/append() parent tr element.
$('#t1 :checkbox').on('change', function() {
var tr = $(this).closest('tr');
var tbody = $('#t1 tbody')
if (this.checked) {
tbody.prepend(tr)
} else {
tbody.append(tr)
}
});
jQuery(function($) {
$('#t1 :checkbox').on('change', function() {
var tr = $(this).closest('tr');
var tbody = $('#t1 tbody')
if (this.checked) {
tbody.prepend(tr)
} else {
tbody.append(tr)
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="t1">
<thead>
<th></th>
<th>Check</th>
<th>ID</th>
<th>Title</th>
</thead>
<tbody>
<tr>
<td>
<input type="checkbox" id="chk1" name="chk1">
</td>
<td>1</td>
<td>Title 1</td>
</tr>
<tr>
<td>
<input type="checkbox" id="chk2" name="chk2">
</td>
<td>2</td>
<td>Title 2</td>
</tr>
<tr>
<td>
<input type="checkbox" id="chk3" name="chk3">
</td>
<td>3</td>
<td>Title 3</td>
</tr>
<tr>
<td>
<input type="checkbox" id="chk4" name="chk4">
</td>
<td>4</td>
<td>Title 4</td>
</tr>
<tr>
<td>
<input type="checkbox" id="chk5" name="chk5">
</td>
<td>5</td>
<td>Title 5</td>
</tr>
</tbody>
</table>
Try this code.
$('table').on('change', '[type=checkbox]', function() {
var $this = $(this);
var row = $this.closest('tr');
if ($this.prop('checked')) { // move to top
row.insertBefore(row.parent().find('tr:first-child'))
.find('label').html('move to bottom');
} else { // move to bottom
row.insertAfter(row.parent().find('tr:last-child'))
.find('label').html('move to top');
}
});
First you have to handle the event on change for the checkboxes, and then if the checkbox is checked you should prepend the tr parent to the tbody of your table.
$("#t1 input:checkbox").on("change",function(){
if(this.checked){
$("#t1 tbody").prepend($(this).parents("tr"))
}else{
$("#t1 tbody").append($(this).parents("tr"))
}
})
Here is a fiddle with your example working
https://jsfiddle.net/kLhxq3Lj/

How to get the position of the checked checkbox in a table

I have a table with bunch of checkboxes in each row. How can I find position of the checked box e.g. 1A or 1B when both or one of the checkboxes is checked in first row. The page I am trying to modify, dynamically makes the table based on two factors for the rows and columns. SO I just need to grab the rowname and colname in order to program further. e.g. 10(A) if the name of first row was '10'.
<table id="mytable">
<tr>
<td> </td>
<td align="center"> A </td>
<td align="center"> B </td>
</tr>
<tr>
<td> 1 </td>
<td><input type="checkbox" /></td>
<td><input type="checkbox" /></td>
</tr>
<tr>
<td> 2</td>
<td><input type="checkbox" /></td>
<td><input type="checkbox" /></td>
</tr>
</table>
<tr> <button id="save">Click</button> </tr>
This will get the column and row of a checked input, and it gets the column letter and row number through calls to document.querySelector, using CSS3 first-child and nth-child selectors based on the column and row:
document.getElementById('mytable').addEventListener('click', function(e) {
if(e.target.tagName === 'INPUT') {
var td= e.target.parentNode, //the input's td parent
tr= td.parentNode, //the td's tr parent
col= td.cellIndex, //the input's column
row= tr.rowIndex, //the input's row
header= document.querySelector('#mytable tr:first-child td:nth-child('+(col+1)+')').textContent,
number= document.querySelector('#mytable tr:nth-child('+(row+1)+') td:first-child').textContent;
document.getElementById('output').textContent= number+header;
}
});
<table id="mytable">
<tr>
<td></td>
<td align="center">A</td>
<td align="center">B</td>
</tr>
<tr>
<td>1</td>
<td>
<input type="checkbox" />
</td>
<td>
<input type="checkbox" />
</td>
</tr>
<tr>
<td>2</td>
<td>
<input type="checkbox" />
</td>
<td>
<input type="checkbox" />
</td>
</tr>
</table>
<div id="output"></div>
try this # plain javascript:
var checkboxes = [];
for(var i =0; i<document.getElementsByTagName("input").length;i++) {
if(document.getElementsByTagName("input")[i].checked) {checkboxes.push(i)}
}
checkboxes is an array of checked checkboxes - e.g. [0,2] if the first and the 3rd checkboxes are checked
or like this:
https://jsfiddle.net/zLy90w40/1/
function getCheckBox(){
var oneA = document.getElementById('1a');
var oneB = document.getElementById('1b');
var twoA = document.getElementById('2a');
var twoB = document.getElementById('2b');
if (oneA.checked){
alert("1 A was checked") ;
}
if(oneB.checked){
alert("1 B was checked") ;
}
if(twoA.checked){
alert("2 A was checked") ;
}
if(twoB.checked){
alert("2 B was checked") ;
}
}

Categories