javascript validation of dynamic checkbox - javascript

Name and id of checkboxes are appearing dynamically. And we are not sure of number of checkboxes. A map is iterated to generate checkboxes contained in a table. So, each table will have a checkbox with 2-3 options depending on map entries. Javascript should validate that at least one entry of checkbox in a table should be checked.
HashMap<ServerGroup, ArrayList<String>> serversMap = (HashMap<ServerGroup, ArrayList<String>>) session.getAttribute("userServersMap");
Iterator itr = serversMap.entrySet().iterator();
while (itr.hasNext()) {
Map.Entry<ServerGroup, ArrayList<String>> entry = (Map.Entry<ServerGroup, ArrayList<String>>)itr.next();
<table border='1' align="center">
<tr>
<th>Select Server</th>
<th>Servers</th>
</tr>
<%
for (String server : entry.getValue()) {
%>
<tr>
<td><input type="checkbox" name="<%= entry.getKey().getName().toString() %>" value="<%=server%>"></td>
<td><%=server%></td>
</tr>
<%
}
%>
</table>

Try this with JS:
function checkOneCheckbox(){
var checkboxes=document.getElementsByName("your_checkbox_name"); //all should be same
var is_checked=false;
for(var i=0;i<checkboxes.length;i++)
{
if(checkboxs[i].checked)
{
is_checked=true;
}
}
if(is_checked){
//at least one is checked;
}else {
//...
}
}
More easy with jQuery:
// onready method...binding
var is_checked = false;
$('input[type="checkbox"]').each(function() {
if ($(this).is(":checked")) {
is_checked = true;
}
});

The following solution should hopefully work in this case.
Let's assume that your JSP generated the following html page
(say two html tables, it can generate any number of tables though for your case):
<table border='1' align="center">
<tr>
<th>Select Server</th>
<th>Servers</th>
</tr>
<tr>
<td><input type="checkbox" name="serverX" value="TestServer1"></td>
<td>TestServer1</td>
</tr>
<tr>
<td><input type="checkbox" name="serverY" value="TestServer2"></td>
<td>TestServer2</td>
</tr>
</table>
<table border='1' align="center">
<tr>
<th>Select Server</th>
<th>Servers</th>
</tr>
<tr>
<td><input type="checkbox" name="serverM" value="TestServer3"></td>
<td>TestServer3</td>
</tr>
<tr>
<td><input type="checkbox" name="serverN" value="TestServer4"></td>
<td>TestServer4</td>
</tr>
<tr>
<td><input type="checkbox" name="serverO" value="TestServer5"></td>
<td>TestServer5</td>
</tr>
</table>
Then on form submit you can call a Validate function which will iterate through all the tables on your page and if it finds a table without any checked checkbox it will return false and simply focus on the first checkbox of the table.
The Validate function will be :
function Validate()
{
var table = document.getElementsByTagName('table'); // get all the tables on the page
for(var i=0; i<table.length;i++) //loop through each table
{
var flag = false;
for( var j=1; j<table[i].rows.length;j++) // start checking from 2nd row of the table
{
var currentRow = table[i].rows[j];
var cell = currentRow.cells[0];
var elem = cell.getElementsByTagName("input");
if (elem[0].type == "checkbox")
{
if(elem[0].checked)
{
flag=true;
break; // stop checking this table as one checked found
}
}
}
if(j==table[i].rows.length && flag == false)
{
alert("Please select at least one checkbox!");
table[i].rows[1].cells[0].getElementsByTagName("input")[0].focus();//focus on the first checkbox in the table
return false;
}
}
}
Hope it helps!
Working Demo:
http://jsfiddle.net/6cyf4skd/

Related

How to perform operations on selected rows in checkbox in a table in HTML

I have a table and I want to perform some operations(suppose doing output of selected rows in alert) on the rows which the user have checked on.
Following is my approach which is failing miserably-
<html>
<head>
<title>Introduction</title>
<script>
function kro(){
var x = document.getElementsByName('checks');
for (var i = 0;i < x.length;i++){
if(x[i].checked == 1)
var selecteddata+=x[i].value+"\n";
}
alert(selecteddata)
}
</script>
</head>
<body>
<table>
<thead>
<tr>
<th>UserName</th>
<th>Post</th>
<th>Comments</th>
<th>Select</th>
</tr>
</thead>
<tbody>
<tr>
<td>Ram</td>
<td>Sahi hai</td>
<td>Ravan:No</td>
<td><input type = "checkbox" name = "checks" id='one'/> </td>
</tr>
<tr>
<td>Ravan</td>
<td>Kidnap done</td>
<td>Ram:I'll kill you</td>
<td><input type = "checkbox" name = "checks" id='two'/> </td>
</tbody>
<p id = "check" ></p>
<button onclick="kro()">
Result
</button>
</body>
</html>
Following is my table-
I want to perform further operations on the selected row ,in the code ,I just want to output the selected rows using alert.
How to do that?
Expected Output-
if first row is checked then
Ram Sahi hai Ravan:No
var selecteddata+=x[i].value+"\n"; line will throw an error, So declare the variable outside the for loop. Also you need to set a value to checkbox otherwise it will so on
To get the content from all the td get the parent of the checkbox and get the closest tr. Then get text from each of the td and add it in a local variable of the if block
function kro() {
var x = document.getElementsByName('checks');
var selecteddata = '';
for (var i = 0; i < x.length; i++) {
if (x[i].checked) {
let _tt = '';
x[i].closest('tr').querySelectorAll('td').forEach(function(item) {
_tt += item.textContent.trim();
})
selecteddata += _tt + "\n";
}
}
alert(selecteddata)
}
<table>
<thead>
<tr>
<th>UserName</th>
<th>Post</th>
<th>Comments</th>
<th>Select</th>
</tr>
</thead>
<tbody>
<tr>
<td>Ram</td>
<td>Sahi hai</td>
<td>Ravan:No</td>
<td><input type="checkbox" name="checks" id='one' value='test1' /> </td>
</tr>
<tr>
<td>Ravan</td>
<td>Kidnap done</td>
<td>Ram:I'll kill you</td>
<td><input type="checkbox" name="checks" id='two' value='test2' /> </td>
</tbody>
<p id="check"></p>
<button onclick="kro()">
Result
</button>
You define and concat to the variable wrong.
should be
var foo = ''; // declare outside of loop
for (var i=0; i<5; i++) {
foo += i + '\n' // concat to string
}
console.log(foo) //display it
Other way people would do it is with an array and joining it at the end
var foo = []; // declare outside of loop
for (var i=0; i<5; i++) {
foo.push(i) // add to array
}
console.log(foo.join('\n')) //display it by joining the array items

Store Table Row Selections Across Multiple Pages

I have a search results table with a checkbox allowing users to select 1 or more rows - this is working fine on a single page at the moment. However I have to use pagination to limit the results to 20 rows per page, so once the user clicks the Next Page button to go to the 2nd page of search results their selections are lost.
Is there a way to keep their selections from page to page?
Here's an example of how the table appears with the script that sets a hidden form input:
$(function() {
//column checkbox select all or cancel
$("input.select-all").click(function() {
var checked = this.checked;
$("input.select-item").each(function(index, item) {
item.checked = checked;
});
// update the hidden input with the selected selectedProductIDs
var items = [];
$("input.select-item:checked:checked").each(function(index, item) {
items[index] = item.value;
});
if (items.length < 1) {
$('#selectedProductIDs').val('');
} else {
var values = items.join(',');
$('#selectedProductIDs').val(values);
}
});
//check selected items
$("input.select-item").click(function() {
var checked = this.checked;
console.log(checked);
checkSelected();
// update the hidden input with the selected assetIDs
var items = [];
$("input.select-item:checked:checked").each(function(index, item) {
items[index] = item.value;
});
if (items.length < 1) {
$('#selectedProductIDs').val('');
} else {
var values = items.join(',');
$('#selectedProductIDs').val(values);
}
});
//check is all selected
function checkSelected() {
var all = $("input.select-all")[0];
var total = $("input.select-item").length;
var len = $("input.select-item:checked:checked").length;
console.log("total:" + total);
console.log("len:" + len);
all.checked = len === total;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<table class="table table-condensed table-striped table-bordered">
<thead>
<th><input type="checkbox" class="select-all checkbox" name="select-all" /></th>
<th class="text-center" scope="col">Product ID</th>
<th class="text-center" scope="col">Description</th>
</thead>
<tbody>
<tr class="" id="85799">
<td><input type="checkbox" class="select-item checkbox" name="select-item" value="AT36288" /></td>
<td>12345</td>
<td>Apples</td>
<td></td>
</tr>
<tr class="" id="85800">
<td><input type="checkbox" class="select-item checkbox" name="select-item" value="AT36289" /></td>
<td>67890</td>
<td>Bananas</td>
<td></td>
</tr>
<tr class="" id="85801">
<td><input type="checkbox" class="select-item checkbox" name="select-item" value="AT36290" /></td>
<td>55441</td>
<td>Oranges</td>
<td></td>
</tr>
</tbody>
</table>
<form class="form-horizontal" id="processSelections" action="processSelections.php" method="post" role="form">
<input type="hidden" name="selectedProductIDs" id="selectedProductIDs" value="">
<div>
<div class="text-center">
<button type="submit" name="buttonType" value="createShipments" id="save" class="btn btn-success">Process Selections</button>
</div>
</div>
</form>
I ended up having the AJAX script call a PHP page which updated a $_SESSION variable with the selected items so this would persist from page to page.

Displaying rows in a table first with checked checkbox

I have table displayed with checkboxes in each row like this-
Html code : -
<table>
<tr>
<td><input type= "checkbox"></td>
<td>Name1</td>
<td>Role1</td>
</tr>
<tr>
<td><input type= "checkbox"></td>
<td>Name2</td>
<td>Role2</td>
</tr>
<tr>
<td><input type= "checkbox"></td>
<td>Name4</td>
<td>Role4</td>
</tr>
<tr>
<td><input type= "checkbox"></td>
<td>Name3</td>
<td>Role3</td>
</tr>
</table>
I also have a button 'Sort'. When I click on the button sort, all those rows which have checkboxes as checked should be displayed first and all other rows after them. The result would look something like this -
How can this be implemented?
Using jquery you can parse each <tr> and check if their child checkbox is check then add them to a new table as first or last child. then replace the old table with the new one.
$(document).ready(function(){
$('#sort').on('click', function(){
var newTable = $('<table class="table"></table>');
$('.table').find('tr').each(function($index, $value){
if($(this).find('input[type=checkbox]').is(':checked')){
newTable.prepend($(this));
} else {
newTable.append($(this));
}
});
$('.table').replaceWith(newTable);
});
});
this should work but i havn't tested it yet.
Hopes it helps !
Nic
You can use sort() and is(':checked') to sort rows and then empty table and append sorted content. DEMO
var sorted = $('table tr').sort(function(a, b) {
if($(b).find('td:first-child input').is(':checked')) {
return 1;
} else {
return -1;
}
})
$('button').click(function() {
$('table').empty().html(sorted);
})
please try this
$('input').each(function(e,i){
if(!i.checked){
var tr=$(i).closest('tr');
$(tr).parent().append($(tr).remove());
}
});

Selecting multiple rows of items in a table

EDIT: I didn't have enough time to ask the question properly. I am rewriting the question with an image.
So, I have a table (shown below):
The data on each row are dynamically filled out.
However, if users want to delete the data (which they can), they have to delete them individually.
How can I implement the "Select" checkbox and apply the "Delete" (for example) action to the "Checked" items?
Thanks! =)
Something like this?
function inputChanged(event) {
event.target.parentElement.parentElement.className =
event.target.checked ? 'selected' : '';
}
function printSelected() {
var textArea = document.getElementsByTagName('textarea')[0];
textArea.value = '';
var selectedRows = document.getElementsByClassName('selected');
for (var i = 0; i < selectedRows.length; ++i) {
textArea.value += selectedRows[i].textContent.trim() + '\n';
}
}
.selected {
background-color: yellow;
}
<table>
<tr>
<td>
<input type="checkbox" onchange="inputChanged(event)" />
</td>
<td>Row 1</td>
</tr>
<tr>
<td>
<input type="checkbox" onchange="inputChanged(event)" />
</td>
<td>Row 2</td>
</tr>
</table>
<button onclick="printSelected()">Print selected rows</button>
<textarea></textarea>

getting the row values with checkbox

hello guys? can you please help with this? i have this tables in HTML.what i want to achieve is that, when i click the row the checkbox will be checked and the row will be highlighted.and is it possible with the checkbox column hidden?
<table border="1" id="estTable">
<thead>
<tr>
<th></th>
<th>Name</th>
<th>Age</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="checkbox"></td>
<td>Chris</td>
<td>10</td>
</tr>
<tr>
<td><input type="checkbox"></td>
<td>Cass</td>
<td>15</td>
</tr>
<tr>
<td><input type="checkbox"></td>
<td>Aldrin</td>
<td>16</td>
</tr>
</tbody>
</table>
<input type="button" value="Edit" id="editbtn"/>
<div id="out"></div>
and i have this javascript to get the values of the selected row.And i was hoping to print one row at a time.
$('#editbtn').click(function(){
$('#estTable tr').filter(':has(:checkbox:checked)').find('td').each(function() {
$('#out').append("<p>"+$(this).text()+"</p>");
});
});
This gets a little easier when you use classes to add more context to your source:
<tr>
<td class="select hidden">
<input type="checkbox">
</td>
<td class="name">Chris</td>
<td class="age">10</td>
</tr>
Then you can do something like this:
$(document).ready(function () {
'use strict';
$('#estTable tbody tr').click(function (e) {
//when the row is clicked...
var self = $(this), //cache this
checkbox = self.find('.select > input[type=checkbox]'), //get the checkbox
isChecked = checkbox.prop('checked'); //and the current state
if (!isChecked) {
//about to be checked so clear all other selections
$('#estTable .select > input[type=checkbox]').prop('checked', false).parents('tr').removeClass('selected');
}
checkbox.prop('checked', !isChecked).parents('tr').addClass('selected'); //toggle current state
});
$('#editbtn').click(function (e) {
var selectedRow = $('#estTable .select :checked'),
tr = selectedRow.parents('tr'), //get the parent row
name = tr.find('.name').text(), //get the name
age = parseInt(tr.find('.age').text(), 10), //get the age and convert to int
p = $('<p />'); //create a p element
$('#out').append(p.clone().text(name + ': ' + age));
});
});
Live demo: http://jsfiddle.net/Lf9rf/
if i understand the "print one row at a time" correctly, i think you need to empty your "out" selector before executing the new call
$('#editbtn').click(function(){
$('#out').empty();
$('#estTable tr').filter(':has(:checkbox:checked)').find('td').each(function() {
$('#out').append("<p>"+$(this).text()+"</p>");
});
});
jsBin demo
CSS:
.highlight{
background:gold;
}
jQuery:
$('#estTable tr:gt(0)').click(function( e ){
var isChecked = $(this).find(':checkbox').is(':checked');
if(e.target.tagName !== 'INPUT'){
$(this).find(':checkbox').prop('checked', !isChecked);
}
$(this).toggleClass('highlight');
});

Categories