How to calculate number of checkboxs'Id in a table via Javascript - javascript

I wanna get the total number of the checkbox in a html.
request:
(1) By Javascript
(2) all my checkbox id is "id=idCheckBox",
(3) each checkbox name is reserved for back-end using. not for javascript.
(4) The naming for each checkbox's name is like checkbox_1, checkbox_2,... where the number indicate the serial number of a checkbox.
The Table Html
<table class="form_table" border="0" cellpadding="0" width="750px" id="idRoutineListTable">
<tr>
<td style="align:center;" class="routineListCell">
<input type='checkbox' name='checkbox_1' id='idCheckBox'></input>
<!-- It may many checkbox here.-->
</td>
</tr>
</table>
My JS code, the function is to check any checkbox is selected before deletion. if no checkbox is selected, it pops up warning.
function beforeDelete() /*{{{*/
{
var checked=0;
var checkboxAll=document.all["idCheckBox"];
//the error is here, when there is only one checkbox, I cannot get length value,
//coz checkboxAll is not recognized as an array. However, if there are more than
//two checkboxes, the function works.
alert (checkboxAll.length);
for(var i=0;i<checkboxAll.length;i++) {
if (checkboxAll[i].checked==true) {
checked++;
}
}
if(checked==0) {
alert('Please select the item you will delete');
return false;
}
} /*}}}*
The problem has indicate in the above code.
Any idea to solve this?

here is a full working sample using jQuery:
<script src="../../Scripts/jquery-1.5.1.js" type="text/javascript"></script>
<script>
function beforeDelete() {
if ($("input:checked").length == 0) {
alert('Please select the item you will delete');
return false;
}
return true;
}
</script>
<form onsubmit="return beforeDelete()">
<table class="form_table" border="0" cellpadding="0" width="750px" id="idRoutineListTable">
<tr>
<td style="align:center;" class="routineListCell">
<input type='checkbox' name='checkbox_1' id='idCheckBox'></input>
<input type='checkbox' name='checkbox_2' id='idCheckBox'></input>
<input type='checkbox' name='checkbox_3' id='idCheckBox'></input>
<!-- It may many checkbox here.-->
</td>
</tr>
</table>
<input type="submit" />
</form>

Try this:
function beforeDelete() {
var checkboxAll=document.getElementsByTagName("input");
for(var i=0;i<checkboxAll.length;i++) {
var input = checkboxAll[i];
if (input.type == "checkbox" && input.checked==true) {
return true;
}
}
alert('Please select the item you will delete');
return false;
}

The first decision:
You may use checkboxAll.length as a condition to check if there is only one checkbox in your markup.
if(checkboxAll.length == undefined)
If not, you may use your code with loop, if it is only one checkbox - check only one.
The second decision:
To use getElementsByTag that will return you an array. In this case you need to filter this array with the given id
Demo for both decisions here

Related

send one or zero with checkbox click in JS

I currently have a form with a loop that builds multiple checkboxes where I can successfully trigger an event.
I have my code set so that if the value from the database for the row is 1 then pre-check the box, which works.
I'm trying to make it so that when the box is checked, Javascript sends a '1' but if it's unchecked then it sends a '0'.
If the page loads with the database value of 1, and the box is checked, then when the user unchecks it I want it to send '0' to the console log and vice versa
<form id="saveLineup">
#foreach($list as $lists)
<tr style="text-align:center;">
<td><input class="addToLineup" type="checkbox" <?php if ($lists['LINE_UP'] == 1) echo "checked='checked'"; ?></td>
</tr>
#endforeach
</form>
currently, no matter what, the checkbox triggers the value 'on' to show on console.log, whether I check or uncheck it.
What am I doing wrong?
$(".addToLineup").click(function (e) {
updatedata.lineup = $(".addToLineup").val();
console.log(updatedata);
});
<form id="saveLineup">
#foreach($list as $lists)
<tr style="text-align:center;">
<td>
<input class="addToLineup" type="checkbox"/>
</td>
</tr>
#endforeach
</form>
Edit: After clarification, you simply need a check for status of the checkbox when it's clicked, then send 1 or 0 based on that:
$(".addToLineup").click(function(e) {
if ($(this).is(":checked")) {
updatedata.lineup = 1;
} else {
updatedata.lineup = 0;
}
console.log(updatedata);
});
JSFiddle for reference: https://jsfiddle.net/1agLdu5e/1
You should set the values of the checkboxes to something that identifies the particular lineup. Then use an array-style name for the input. The result will be that $_POST['addToLineup'] will be an array of all the identifiers.
<form id="saveLineup">
#foreach($list as $lists)
<tr style="text-align:center;">
<td><input class="addToLineup" name="addToLineup[]" type="checkbox" value="<?php echo $lists['ID']; ?>" <?php if ($lists['LINE_UP'] == 1) echo "checked='checked'"; ?></td>
</tr>
#endforeach
</form>
Replace 'ID' with the actual name of the table column containing the lineup ID.

How do I check multiple checkboxes with jquery without giving each an id?

I am trying to check multiple checkboxes using one with jQuery. I know how to do this to check all checkboxes or to check multiple if they have ids. I want to be able to do this without that though.
All of my checkboxes are in a similar grouping. I have them grouped in a consistant way.
I have my work on a fiddle here.
Here is my code
window.onCheck = function () {
var totals = [0, 0, 0];
$('tr.checkRow').each(function () {
var $row = $(this);
if ($row.children('td:first').find('input:checkbox').prop('checked')) {
$(this).find('td.imageBox').each(function (index) {
var $imageBox = $(this);
if ($imageBox.children('img:first').attr('src').indexOf('yes') >= 0) {
++(totals[index]);
}
});
}
});
$('#total1').text(totals[0]);
$('#total2').text(totals[1]);
$('#total3').text(totals[2]);
};
window.onCheckForm = function (cb) {
var $cb = $(cb);
var $table = $cb.parents("table");
$('input.subFieldCheck').find($table).prop('checked', function () { return cb.prop('checked')});
}
My problem is with the onCheckForm function.
Thank you.
Note: I started writing this answer for a duplicate of this question and realized I couldn't post this, so I posted it here instead. The table structure is different and a lot simplified in this answer.
Lets start off with a very simple table with a checkbox column:
<table>
<thead>
<tr>
<th scope='col' id='toggler'>
<input type='checkbox' id='toggleAll'>
<label for='toggleAll'>Select all</label>
</th>
<th scope='col'>A column</th>
</tr>
</thead>
<tbody>
<tr>
<td headers='toggler'>
<input type='checkbox'>
</td>
<td>some cell data</td>
</tr>
<tr>
<td headers='toggler'>
<input type='checkbox'>
</td>
<td>some cell data</td>
</tr>
<tr>
<td headers='toggler'>
<input type='checkbox'>
</td>
<td>some cell data</td>
</tr>
<tr>
<td headers='toggler'>
<input type='checkbox'>
</td>
<td>some cell data</td>
</tr>
<tr>
<td headers='toggler'>
<input type='checkbox'>
</td>
<td>some cell data</td>
</tr>
</tbody>
</table>
Here, I have a checkbox in the header along with a label for accessibility purposes (you may hide the label if you wish).
I've also given the header cell an ID and used the headers attribute for the td elements. This isn't absolutely necessary for what we're doing, however it seems like an appropriate case to use the headers attribute. If you ever want to move the checkbox to another column for certain rows, you can just add the headers attribute to that cell.
Here is some JavaScript code:
$('#toggleAll').change(function () {
$('td[headers~="toggler"] > input[type="checkbox"]').prop('checked', $(this).prop('checked'));
});
We are binding a function to the change event to the checkbox in the header.
The selector will look for all checkboxes that are children of td elements that contain the ID toggler in a space-separated list of tokens in the headers attribute.
The .prop() method sets the checked property of the checkboxes to match the value of the checked property of the one in the header ("this").
Our basic functionality is done here.
We can make improvements though, by changing the state of the checkbox at the top to match the state of the checkboxes in the rows.
The state of the header checkbox should be:
Unchecked if 0 are checked
Interdetermine if (0, n) are checked
Checked if n are checked
Where n indicates all the checkboxes.
To do this, we bind a function to the change event of each of the boxes in the table rows:
$('td[headers~="toggler"] > input[type="checkbox"]').change(function() {
var allChecked = true, noneChecked = true;
var headerCheckbox = $('#toggleAll');
$('td[headers~="toggler"] > input[type="checkbox"]').each(function(i, domElement) {
if(domElement.checked) {
// at least one is checked
noneChecked = false;
} else {
// at least one is unchecked
allChecked = false;
}
});
if(allChecked) {
headerCheckbox.prop('checked', true);
headerCheckbox.prop('indeterminate', false);
} else if (noneChecked) {
headerCheckbox.prop('checked', false);
headerCheckbox.prop('indeterminate', false);
} else {
headerCheckbox.prop('indeterminate', true);
}
});
I'm using .each() here to loop through all of the appropriate checkboxes to determine whether all, none, or some are checked.
See the jsFiddle demo.
Hope this helps, I sure learned quite a bit while answering the question!
See this fiddle for a cleaner way:
http://jsfiddle.net/W75dy/19/
<td class="field">
<form class="fieldCheck">
<input type="checkbox" id="Row1Chk" name="Row1" value="Row1" />
</form> Programs
</td>
$('#Row1Chk').on('change', function(event) {
$('table.checkTable input[type=checkbox]').prop('checked', $(this).prop('checked'));
});

Javascript error, updating checkboxes/buttons base don result of other checkboxes

first a quick description:
I have 4 tables (1 and 3 contain a line of checkboxes, 2 and 4 contain radio buttons).
What I am looking to do is have it so that when I select a checkbox in table 1, it updates tables 2,3,4 by setting the equivalent checkbox to 'disabled'.
I figure the easiest option is to use the 'VALUE' attribute, as this will be the same on each table (e.g. the field with VALUE 4 on the first table will be the equivalent of the field with VALUE 4 on the others).
My tables all have a unique ID per table, and share a classname of 'TableClassName'.
They all look similar to:
<table id="TableID1" class="TableClassName">
<tr>
<th class="CellGrey">1</td>
<th class="CellGrey ">2</td>
<th class="CellGrey ">3</td>
<th class="CellGrey ">4</td>
</tr>
<tr>
<td class="CellRed "><INPUT TYPE="checkbox" NAME="ignore[]" VALUE="1" checked></td>
<td class="CellWhite "><INPUT TYPE="checkbox" NAME="ignore[]" VALUE="2"></td>
<td class="CellWhite "><INPUT TYPE="checkbox" NAME="ignore[]" VALUE="3"></td>
<td class="CellWhite "><INPUT TYPE="checkbox" NAME="ignore[]" VALUE="4"></td>
</tr>
</table>
So far what I have is:
script type="text/javascript">
$(document).ready(function()
{
$("#TableID1").on('click','input:checkbox',function()
{
if ($(this).attr('checked'))
{
var $val = $(this).attr('value');
//alert($val);
$(".DBSelectTable td").function()
{
if ($(this).child().attr('VALUE') == $val)
{
$(this).child().attr('disabled');
}
}
}
}
)
}
);
</script>
But, I am getting the error:
"Uncaught Type Error: Object[object Object] has no method 'function' "
my theory is simple:
Select the #TableID1 table
find out which box in the first table has been clicked and get the VALUE attribute
Select the .TableClassName tables
check if any have the same VALUE, and add the 'disabled' attribute
but something is wrong, and I can't see where to go from here. Any help would be appreciated.
note that I use prop instead if attr.
also, you can compare the values in the find function.
$(document).ready(function()
{
$("#TableID1").on('change','input:checkbox',function()
{
if ($(this).prop('checked'))
{
var val = $(this).val();
$(".DBSelectTable td").find("[value='"+ val +"']").prop('disabled',true)
}
}
)
}
);

Field.length not working on a single checkbox

I have a form which contains list of data, I added a checkbox in from of each, when I click on the uppermost checkbox it selects all. But if I have just one row of data and I click on the upper most checkboxes dont work. Here is the script below.
////checking all checkbox on page
function checkAll(field)
{
// alert(field.length);
for (i = 0; i < field.length; i++){
field[i].checked = true ;
}
}
////unchecking all checkbox on page
function uncheckAll(field)
{
for (i = 0; i < field.length; i++){
field[i].checked = false;
}
}
function selectCHK(e){
if(e.checked==true){
//alert("Yeah");
checkAll(document.paginate_list.list);
}else{
uncheckAll(document.paginate_list.list);
}
}
function ApplyToSelected(){
var SelectedVal="";
var withSelected=document.getElementById("withSelected");
//
if(withSelected.value==1){
//if(document.getElementById("list")){
// SelectedVal=document.getElementById("list").value;
//}
for(i=0; i<document.paginate_list.list.length;i++){
if (document.paginate_list.list[i].checked) {
//alert(i);
SelectedVal +=document.paginate_list.list[i].value+",";
}
}
if(SelectedVal==""){
return false;
}
if(confirm("Are you Sure you want to Delete the Selected Row?")){
$.ajax({
url: "../__lib__/pagingLib.php?tableDeleteID="+SelectedVal,
context: document.body,
success: function(response,status,xhr){
if(response==1){
alert("Deleted Successfully");
window.location.reload();
}else{
alert(response);
alert("An Error Occurred while Deleting, Please Try Again!");
}
// alert(response);
}
});
}
}
}
HTML DATA
<form name="paginate_list" style="display:inline;" action="" method="post">
<table class="PagingBody">
<tr>
<th><input type=checkbox onclick=selectCHK(this) ></th>
<th>Category Title</th><th>Actions</th>
</tr>
<tr class="even">
<td><input name=list[] type=checkbox id=list value=10></td>
<td>Web Design</td>
<td><a href=?page=cat&edit=10>Edit</a> | <a href=#10>Delete</a></td>
<tr/>
</table>
<table>
<tr>
<td>
<select name="withSelected" id="withSelected">
<option value="0">With Selected</option>
<option value="1">Delete</option>
</select>
<input type="button" name="applyToSelected" id="applyToSelected" value="Apply to Selected" onclick="ApplyToSelected()" />
</td>
<tr/>
</table>
</form>
paginate_list.list represents the name of my form and the list name.
This fiddle will demonstrate what's happening
FIDDLE HERE
The reason why this is happening is because the browser generates a NodeList when you have more than one element in the list that you send to the function checkAll();
Otherwise you just get the normal input element.
I added an instanceof check to see what type of object it was.
To check for this in IE follow this thread here on SO:
NodeList check in IE
Good luck!

Javascript: Validating dynamically created radio button list control in ASP.NET

I have an ASPX page where in the page load i am dynamically creating some radio button list controls and rendering to browser.I will have 2 list items in each radio button list .One is Yes and second is No. The number of Radio buttonlist can be n.Now in my java script code, i want to know which radio button is clicked . I m already using jQuery .any easy way to handle this ?
My HTML rendered to browser is
<table border="0" id="tblQuestions">
<tr>
<td>Do you have a valid passport ?</td>
</tr><tr>
<td><table id="answer-1" border="0">
<tr>
<td><input id="answer-1_0" type="radio" name="answer-1" value="1" /><label for="answer-1_0">Yes</label></td>
</tr><tr>
<td><input id="answer-1_1" type="radio" name="answer-1" value="0" /><label for="answer-1_1">No</label></td>
</tr>
</table></td>
</tr><tr>
<td>Are you married ?</td>
</tr><tr>
<td><table id="answer-2" border="0">
<tr>
<td><input id="answer-2_0" type="radio" name="answer-2" value="1" /><label for="answer-2_0">Yes</label></td>
</tr><tr>
<td><input id="answer-2_1" type="radio" name="answer-2" value="0" /><label for="answer-2_1">No</label></td>
</tr>
</table></td>
</tr>
</table>
Thanks in advance
The following code doesn't specifically answer your question, but it might help. I'd modify it for you, but I just don't have the time right now.
I use this on exams, to warn the user that a particular question doesn't have a selected answer.
The questions are generated dynamically using a Server control which emits plain xhtml. I name all options with the same name, (Q1, Q2...), and ID them like (Q1a, Q1b ...)
To modify it for your purposes, perhaps you could build a list of selected options in the j loop, that is, adding name -value pairs where the "break" statement is.
// Grabs all inputs - radio, checkbox, text, buttons and lists -sticks them in an array
allInputs = document.getElementsByTagName("input");
var last = "NameUnlikelyToBeUsedAsAnElementName";
// walk through the array
for (i = 0; i< allInputs.length; i++)
{
var input = allInputs[i];
if (input.name == last) continue; // if this object name is the same as the last checked radio, go to next iteration
// checks to see if any one of similarly named radiobuttons is checked
else if (input.type == "radio" )
{
last = input.name;
var radios = document.getElementsByName(input.name);
var radioSelected=false;
//iterate over question options
for (j=0; j < radios.length; j++)
{
if(radios[j].checked)
{
radioSelected=true;
break; // Found it, proceed to next question
}
}
if (!radioSelected) // no option selected
{ // warn user, focus question
alert("You did not answer question " + input.id.substring(0,input.id.length-1));
input.focus();
return false;
}
}
}
return true;
This is with the assumption that you already have jquery included in your page.
define a class on your radio button items, basically your client side HTML should look like <input id="answer-2_1" type="radio" name="answer-2" value="0" class="myrdo" />
now, in your js code, simply wire up an event handler on the class
$(".myrdo").bind("click",function(){if($(this).attr("checked")==true) {alert($(this).val);} });
the above command will simply alert the value of the selected radio button.

Categories

Resources