I have a page with a table on it. Two of the columns in the table are checkbox columns. Each has a different Id value. I'm trying to count, via jQuery, the number of rows in the table where one of the checkbox columns (which has an Id value of 'InChecklist') is checked. My JS function looks as follows:
function UpdateCount() {
var totalRows = $('#checklistTable tbody tr:visible').length;
var totalSeen = $(":input#InChecklist[checked='checked']").length;
$("#rowCount").text(totalRows.toString() + " species / " + totalSeen + " seen")
}
The total row count is fine. But I must not have the syntax correct for the total seen because I cannot get it to count correctly (the value is always zero). If I remove the '#InChecklist', I do get a value greater than zero, but in this case, it's counting the total checked in both checkbox columns, not the one with an Id of 'InChecklist'.
If it helps, the portion of my HTML that renders the checkboxes look as follows. It's MVC5.
<td>
<input id="InChecklist" name="item.HasBeenSeenChecklist" type="checkbox" value="true" /><input name="item.HasBeenSeenChecklist" type="hidden" value="false" />
</td>
<td>
<input id="InLifelist" name="item.HasBeenSeenLifelist" type="checkbox" value="true" /><input name="item.HasBeenSeenLifelist" type="hidden" value="false" />
</td>
Specify the ID before the :input like this
var totalSeen = $("#InChecklist:input[checked='checked']").length;
Edit
var totalSeen = $("input#InChecklist:checked").length;
EDITED:
you can try:
var totalSeen = $("#InChecklist input:checked").length;
selects all the children inputs of #InChecklist
alternatively you can use this:
var totalSeen=0;
$("#InChecklist input").each(function(){
if($(this).is('checked')){
totalSeen++;
}
});
Related
I have a scenario where I am populating a datatable with n number of rows. The rows are populated in groups with a particular group id. Say, if there are 20 rows and they are divided into 4 groups, the first 5 rows will have a group id = 1, and the next 5 rows will have group id = 2 and so on. Each row will have its group id stored in a variable while creating the table.
My task is to give checkboxes to all the rows in a group but make only the first row of a particular group clickable. If the user checks/unchecks the first checkbox of a particular group, all checkboxes of that particular group are checked/unchecked.
I am achieving this by concatenating a counter with the id element of each row and then running a loop through the entire table on each row comparing the current row with its previous row on group id. If the group id of the current row is the same as previous row, it will get the state of checkbox of previous row and make the current checkbox the same state. Nothing is done if the group id of current row is different from previous row.
The problem here is, this logic is working absolutely fine but only once. The checking/unchecking all boxes works only after that it just checks/unchecks that particular box but not for the whole group.
Will provide more info if required.
Thanks
function checkBoxTick(){
for(var i = 0; i<$('#grouprowcount').val(); i++){
if(i != 0){
var previd = $('#groupId'+(i-1)).val();
var nextid = $('#groupId'+(i)).val();
if(previd == nextid ){
$("#numid"+(i)).attr("checked", true);
if($("#numid"+(i-1)).is(":checked")){
$("#numid"+(i)).attr("checked", true);
}
else if($("#numid"+(i-1)).is(":not(:checked)")){
$("#numid"+(i)).attr("checked", false);
}
}
}
}
Please, check if this is what you need, otherwise I suggest you to show us a snippet of your own code.
var groupCount = 2;
for(var i = 1; i <= groupCount; i++)
$(':checkbox').filter('[name="group-'+i+'"]').not(':first').prop('disabled', true);
$(':checkbox').not(':disabled').change(function() {
var group = $(this).attr('name');
var checked = $(this).prop('checked');
$(':checkbox').filter('[name="'+ group +'"]').prop('checked', checked);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<table>
<tr><td><input type="checkbox" name="group-1" /></td></tr>
<tr><td><input type="checkbox" name="group-1" /></td></tr>
<tr><td><input type="checkbox" name="group-1" /></td></tr>
<tr><td><input type="checkbox" name="group-2" /></td></tr>
<tr><td><input type="checkbox" name="group-2" /></td></tr>
<tr><td><input type="checkbox" name="group-2" /></td></tr>
</table>
I have a function where I'm trying to add the total number of checkboxes ticked to a value that is already displayed in the textbox. The solution I have works but it doesn't update properly if I uncheck the boxes and click total again.
Is there a way I can fix this so that the textbox updates accordingly?
HTML
<td><input type="text" name="Yeses" id="NumberofRisks" class = "form-control" value ="<?php echo $row['Total-Score'];?> " style = "width:50px"></td>
Javascript
function sum()
{
sumField = document.getElementById("NumberofRisks");
var sum = sumField.value;
$("input[name^='yanswer']:checked").each(function(){
sum++;
});
sumField.value = sum;
}
You are updating the value of the input after every call to function sum().
Instead have the initial sum value.
Then every time use this value.
var initial = $("#NumberofRisks").val();
function sum()
{
$("#NumberofRisks").val(initial + $("input[name^='yanswer']:checked").length);
displayRating($("#NumberofRisks").val());
}
Keep the original value of the textbox in a variable. Add an event listener to the checkboxes that count the number of checked boxes and adds that number to the original value, then updates the textbox.
Something like this:
HTML:
<input type="checkbox" class="check" />
<input type="checkbox" class="check" />
<input type="checkbox" class="check" />
<input type="textbox" class="text" />
JS:
//Store the original value. The 5 here should be whatever was supposed to be in the textbox.
var originalValue = 5;
$('.text').val(originalValue);
$('.check').on('change', function() {
//Count the number of checked boxes and add it to the original value for display.
var checked = $('.check:checked').length;
$('.text').val(originalValue+checked);
});
Here's a fiddle.
I have the following code which adds together checkboxes when they are selected and produces a total at the bottom of the page. This function uses the following code:
<script type="text/javascript">
function checkTotal() {
document.listForm.total.value = '';
var sum = 68.50;
for (i=0;i<document.listForm.choice.length;i++) {
if (document.listForm.choice[i].checked) {
sum = sum + parseFloat(document.listForm.choice[i].value);
}
}
document.listForm.total.value = sum.toFixed(2);
}
</script>
These checkboxes are within a form, and I need the form to send through to an email account. At the moment because all the checkboxes share the same input name 'choice' the PHP will only send the last checked box value.
I need to change the checkboxes input name code to name the different checkboxes 'choice1' 'choice2' 'choice3'. What would I have to change in the javascript to in order for the function to calculate all the checkboxes names 'choice1' 'choice2' 'choice3' etc rather than just adding together all checkboxes named'choice'? I have little Javascript and PHP knowledge so any help would be grateful. Thanks.
Rather than make the checkbox names unique, it would be better to append "[]" to their name. This will cause PHP to convert the values into an array, rather than just keep the last value.
So you would want a name of choice[] rather than choice.
You can also find some sample code in this answer.
The code below works ok (a self contained web page). The problem is how to get the array (group) of checkboxes when they're called different names. If you use jquery you could give them all the same class, then get hold of them by that class, but if you're using bare javascript then you can get the elements by Tag name ("input" in the case of the checkbox), and check each one has a name attribute that starts with "choice", inoring those that don't start with "choice", like buttons (also an input) or maybe other checkboxes with different names. It's a bit inefficient if the page is huge, unless you group the checkboxes some way.
To group them, you cold put them in a tag like
`<div id="checkboxes"> (checkboxes go here) </div>`
then use
`var cb = document.getElementById("checkboxes");`
`var arrInputs =cb.getElementsByTagName("input");`
for the line to get the arrInputs array. This would just get input type elements from within the Div. Hwever I dind't want to assume the page layout allows your checkboxes to be put in one div
Hope this helps
Doug
<script type="text/javascript">
function checkTotal() {
document.forms.listForm.total.value = '';
var sum = 68.50;
var frm=document.forms.listForm; // wasnt sure what your original listForm element was so I've put this form into a variable, frm
frm.total.value = '';
var arrInputs =document.getElementsByTagName("input"); // get all Input type elements on the form
for (i=0; i < arrInputs .length;i++) {
if (arrInputs[i].name.substr(0,6) == "choice") { // if the name starts with "choice"
if (arrInputs[i].checked) {
sum = sum + parseFloat(arrInputs[i].value);
}
}
}
frm.total.value = sum.toFixed(2);
}
</script>
</head>
<body>
<form name="listForm">
<a href='javascript:checkTotal()'>check</a><br>
<input type=checkbox name="choice1" value="1"><br>
<input type=checkbox name="choice2" value="2"><br>
<input type=checkbox name="choice3" value="3"><br>
<input type=checkbox name="choice4" value="4"><br>
<input type=checkbox name="choice5" value="5"><br>
<input type=checkbox name="choice6" value="6"><br>
<br>
<input type=text name=total value=""><br>
</form>
</body>
</html>
I am trying to force a user to select a radio option on a page, but when the user checks the 'No' option, my .checked value is coming up false.
var long = document.getElementById('long');
if(long.checked == false){
message += '- Please select your stance\\r\\n';
errors = true;
}
<input name='long' id='long' type='radio' value='Yes' >Yes
<input name='long' id='long' type='radio' value='No' >No
Both of your inputs have an id of "long", so getElementById is probably returning the first one, which is the "Yes" button.
You can't give two elements the same "id" value. You could use .getElementsByName() to find the set of radio buttons, and then look for the one that's checked, or give them two different "id" values (which is what I'd probably do).
<input name='long' id='long_yes' type='radio' value='Yes'>Yes
<input name='long' id='long_no' type='radio' value='No'>No
IDs must be unique, according to the HTML spec, therefore your code will not work as written.
If you look at it from a FORM approach, the radio buttons are an array:
var radios = document.form1.long
for(var x=0;x<radios.length;x++) {
alert(radios[x].value)
}
So you can check if YES is selected like this because YES is the first element in the array.
var radios = document.form1.long
if(radios[0].checked) { ... }
You can't have two checkboxes with the same ID property. Give them each a different ID and it should work properly.
var long = document.getElementById('longNo');
if(long.checked == false){
message += '- Please select your stance\\r\\n';
errors = true;
}
<input name='long' id='longYes' type='radio' value='Yes' >Yes
<input name='long' id='longNo' type='radio' value='No' >No
Both radio buttons have the same ID so it is only getting the first one from the getElementById call.
Change your code to use document.getElementsByName("long") then loop over and check each one:
var long = document.getElementsByName('long'), message = "";
var checked = false;
for (var i = 0; i < long.length; i++) {
if (long[i].checked) {
checked = true;
}
}
if(!checked){
message += '- Please select your stance\\r\\n';
alert(message);
}
With none checked - http://jsfiddle.net/myFhm/
With no checked - http://jsfiddle.net/myFhm/1/
You have the same id for both radio buttons, the names need to stay the same but they must have different ids
Try this:
var longYes = document.getElementById('longYes');
var longNo = document.getElementById('longNo');
if(longYes.checked == false && longNo.checked == false){
message += '- Please select your stance\\r\\n';
errors = true;
}
<input name='long' id='longYes' type='radio' value='Yes' >Yes
<input name='long' id='longNo' type='radio' value='No' >No
I have a list of checkbox
<input type="checkbox" name="box1" id="box1" value="x1">X1
<input type="checkbox" name="box1" id="box1" value="x2">X2
<input type="checkbox" name="box1" id="box1" value="x3">X3
The name of the checkbox and the count of checkbox is dynamic.
To retrieve the values of selected checkbox i am using the function as
var urls = "";
var values = "";
var fldname = "box"+i;
$('#'+fldname+':checked').each(function() {
values += $(this).val() +"|";
});
Say I have selected X1 and X3 then in Mozilla the value of "values" is
X1 | X3
While in IE it is just X1.
Please help.
I don't know how your code worked in Mozilla because your syntax is wrong.
You've given all your checkboxes names, but are querying for them using IDs
You need something like
$('[name="' + fldname + '"]:checked');
This basically looks for elements with the given name. You can make it more specific
$('input[name="' + fldname + '"]:checkbox:checked');
Here's an example that doesn't use your iteration : http://jsbin.com/ikifi5