A checkbox for selecting all checkboxes generated by CheckBoxFor - javascript

I am using CheckBoxFor to create a form of a bunch of checkboxes. I have added a class to these checkboxes but since CheckBoxFor doesn't add the class to the hidden false checkbox, I can't select groups of these generated checkboxes based upon it.
Here's a sample of the checkbox table that gets generated. When I hit the "Select All" checkbox (the top most one), I want all the checkboxes in that column to be selected. I do not want the whole table selected, just the column.
Some of the relevant HTML:
<td><input type="checkbox" name="selectAll" value="NBTC" /></td>
<td><input type="checkbox" name="selectAll" value="Contractors" /></td>
<td><input type="checkbox" name="selectAll" value="Coordinators" /></td>
<td><input type="checkbox" name="selectAll" value="NGO" /></td>
<td><input type="checkbox" name="selectAll" value="Public" /></td>
Example of the CheckBoxFor statements I'm using:
#Html.CheckBoxFor(m => m.NBTCGroup.NBTC_FA_Centroid, new {#class = "NBTC"}
This is the JS I was working with, but since the it's selecting based off the class, it doesn't work to select and unselect all as the false checkbox doesn't have the class added to it.
$(document).ready(function () {
$('input[name="selectAll"]').click(function () {
var source = $(this);
var sourceName = $(this).val();
if (sourceName == 'NBTC') {
var checkboxes = document.querySelectorAll('input[class="NBTC"]');
}
else if (sourceName == 'Contractors') {
var checkboxes = document.querySelectorAll('input[class="Contractors"]');
}
else if (sourceName == 'Coordinators') {
var checkboxes = document.querySelectorAll('input[class="Coordinators"]');
}
else if (sourceName == 'NGO') {
var checkboxes = document.querySelectorAll('input[class="NGO"]');
}
else if (sourceName == 'Public') {
var checkboxes = document.querySelectorAll('input[class="Public"]');
}
for (var i = 0; i < checkboxes.length; i++) {
if (checkboxes[i] != source)
checkboxes[i].checked = source.checked;
}
});
Anybody have any ideas on another way to do this?

From your code I assume you are adding NBTC, Contractors, etc classes to each group of checkboxes... you also have several selectAll checkboxes, for each group.
You can change your jQuery like this:
$('input[name="selectAll"]').click(function() {
var className = $(this).val(); // <-- get the group: NBTC, Contractors, etc
$('.' + className).prop('checked', this.checked);
// generates something like this: $('.NBTC').prop('checked', this.checked);
});
I have used this answer for check/uncheck logic.

Related

tetxtbox enable/disable on checkbox select/unselect using Javascript

I have a table with three columns and multiple rows. 2nd and third column consist of a textbox(first child of a container) and a checkbox respectively.
Textbox
<td class="SBS1 c4">
<input class="Medium InputText" type="text" name="QR~QID33#1~1~1~TEXT" id="QR~QID33#1~1~1~TEXT" value="" disabled="">
<label class="offScreen" for="QR~QID33#1~1~1~TEXT">&nbsp; - &nbsp; - hh</label>
</td>
Checkbox
<td class="SBS2 c7">
<input type="checkbox" id="QR~QID33#2~1~1" name="QR~QID33#2~1~1" value="Selected">
<label class="q-checkbox q-checked" for="QR~QID33#2~1~1"></label>
<label class="offScreen" for="QR~QID33#2~1~1">&nbsp; - 󠆺random text</label>
</td>
I have to disable and enable the textboxes in each row on checkbox check and uncheck respectively using javascript. but there seem to be some pagelifecycle issues with the script I am using. Here is the Javascript that I am using in my Qualtrics survey JS interface,
Qualtrics.SurveyEngine.addOnload(function()
{
/*Place Your JavaScript Here*/
var count=document.getElementsByClassName("q-checkbox").length;
for(var i=0;i<count;i++)
{
document.getElementsByClassName("q-checkbox")[i].parentNode.addEventListener("click",hideFunc);
}
function hideFunc()
{
console.log(this.className);
if(this.classList.contains("checkers"))
{
//this.classList.toggle("checkers");
this.previousSibling.previousSibling.previousSibling.firstChild.disabled="false";
this.classList.add("checkers");
return;
}
else
if(!(this.classList.contains("checkers")))
{
this.previousSibling.previousSibling.previousSibling.firstChild.disabled="true";
this.classList.remove("checkers");
return;
}
}
});
I am just trying to toggle or add/remove the class "checkers"and setting "disabled" property of the texboxes accordingly. The code above in HideFunc is one of the work-around I have tried but it is not working.
Is there another way to check for checkbox change?
As the first comment hinted, a better approach is to check the status of the checkbox rather than add/remove a class. Also, making use of prototypejs makes it easier. Try this:
Qualtrics.SurveyEngine.addOnload(function() {
var qid = this.questionId;
$(qid).select('tr.Choice').each(function(choice,idx) { //loop through each row
var cbox = choice.select('td.SBS2').first().down(); //cbox enables 1st question in row
var txtEl = choice.select('td.SBS1').first().down(); //text input to be enabled/disabled
if(cbox.checked == false) { //initialize text input disabled status
txtEl.value = null; //blank text input
txtEl.disabled = true; //disable text input
}
cbox.on('click', function(event, element) { //enable/disable text input on cbox click
if(cbox.checked == false) { //unchecked
txtEl.value = null; //blank text input
txtEl.disabled = true; //disable text input
}
else { //checked
txtEl.disabled = false; //enable text input
}
}); //end on function
}); //end row loop
});
This is another solution I could come up with ,apart from the correct solution by T. Gibbons
var $j= jQuery.noConflict();
$j("td.SBS2 ").click(function(){
$j(this).closest("tr").find(".InputText").prop("disabled",$j(this).children("input")[0].checked);
$j(this).closest("tr").find(".InputText").prop("value","");
var len=document.getElementsByClassName("InputText").length;
for(var i=0;i<=len;i++)
{
document.getElementsByClassName("InputText")[i].style.width="300px";
}
});

How to get value of many selected radio buttons

I'm using JavaScript to get value from the radio boxes to insert it to the database as a string. What I need is that I have more than 2 radio boxes. How would I make use of Javascript to add the values to my database?
Here is my code:
<td>
<input type="radio" name="company_grp" class="largerCheckbox" value='Sentinel' checked="checked">
Sentinel GM
</td>
<td>
<input type="radio" name="company_grp" class="largerCheckbox" value='GuardTrack'>
GuardTrack
</td>
<td>
<input type="radio" name="company_grp" class="largerCheckbox" value='GuardingProduct'>
Guarding Product
</td>
if (!document.frmAdd_Visit.company_grp[0].checked && !document.frmAdd_Visit.company_grp[1].checked && !document.frmAdd_Visit.company_grp[2].checked) {
alert("Please Select the company group does this client belong's to!");
form.company_grp.focus();
return false;
}
It's very tricky but I don't get the correct value. When I select the 3rd radio, it doesn't add to the database but instead it reloads the page.
you can use jquery to get value form radio box
$(document).ready(function(){
$('input[name="company_grp"]:checked').val();
});
The jquery code below returns the value:
$('input[name=company_grp]:checked').val()
can use radio type checked as $(':radio:checked')
var selectedvalue;
if($(':radio:checked').length > 0){
$(':radio:checked').each(function (i) {
selectedvalue = $(this).val();
});
}
console.log(selectedvalue);
Here what I found and it working well for me.
function test_company_grp() {
var radios = document.getElementsByName("company_grp");
var found = 1;
for (var i = 0; i < radios.length; i++) {
if (radios[i].checked) {
alert(radios[i].value);
found = 0;
break;
}
}
if(found == 1)
{
alert("Please Select the company group does this client belong's to!");
}
}

JQuery To check all checkboxes in td based on classname of tr

here is my sample code
<table id="accessListTable">
<tr class="ui-grid groupHead">
<td><input type="checkbox" class="groupHeadCheck"/></td>
</tr>
<tr>
<td><input type="checkbox" id="1"/></td>
</tr>
<tr>
<td><input type="checkbox" id="2"/></td>
</tr>
<tr>
<td><input type="checkbox" id="3"/></td>
</tr>
<tr class="ui-grid groupHead">
<td><input type="checkbox" class="groupHeadCheck"/></td>
</tr>
<tr>
<td><input type="checkbox" id="4"/></td>
</tr>
</table>
E.g, When the checkbox in first row with class groupHeadCheck, all the checkboxex of id 1, 2 and 3 will also be checked.
And if all the checkboxes of 1, 2, and 3 are already checked, the checkbox in first row will be checked.
Please any help!
You can add a click handler to the group checkbox then inside the handler you can find its tr element and the tr's next sibling element till the next occurrence of tr.groupHead
$(function ($) {
$(".groupHeadCheck").on("click", function (event) {
$(this).closest('tr').nextUntil('tr.groupHead').find('input[type="checkbox"]').prop('checked', this.checked)
})
});
Demo: Fiddle
I am sure it can be done in a prettier manner, but this is the basic idea:
$("table tbody").on("change", "input[type=checkbox]", function (e) {
var currentCB = $(this);
var isChecked = this.checked;
if (currentCB.is(".groupHeadCheck")) {
var allCbs = currentCB.closest('tr').nextUntil('tr.groupHead').find('[type="checkbox"]');
allCbs.prop('checked', isChecked);
} else {
var allCbs = currentCB.closest('tr').prevAll("tr.groupHead:first").nextUntil('tr.groupHead').andSelf().find('[type="checkbox"]');
var allSlaves = allCbs.not(".groupHeadCheck");
var master = allCbs.filter(".groupHeadCheck");
var allChecked = isChecked ? allSlaves.filter(":checked").length === allSlaves.length : false;
master.prop("checked", allChecked);
}
});
and if you need to run the code to force the check all state
$(".groupHead").next().find("[type=checkbox]").change();
JSFiddle
This would check all if the first is checked (or uncheck all)
$(document).on('click', '.groupHeadCheck',function() {
$(this).closest('tr').nextUntil('tr.groupHead').find('input[type="checkbox"]').prop('checked', $(this).prop('checked'))
});
you could fiddle a bit with your classes (or IDs) to make it right for you
I know this is already answered, but I wanted a more generic way of doing this. In my case, I wanted to check all in a column until I hit a new group. I also had 3 columns with checkboxes. The ones in the first checkbox column all had names starting with "S_", the second "A_" and the third "C_". I used this to pick out the checkboxes I wanted. I also didn't name the heading checkboxes that were used to do the "check all" so it would stop when it hit the next groupings row.
You could use the class name to apply the same logic.
First, here is what a check all checkbox looked like:
<td>
<input type="checkbox" onchange="checkAll(this, 'S_');" />
</td>
Then the javascript function it calls when clicked:
function checkAll(sender, match)
{
var table = $(sender).closest('table').get(0);
var selector = "input[type='checkbox'][name^='" + match + "']";
for (var i = $(sender).closest('tr').index() + 1; i < table.rows.length; i++)
{
var cb = $(table.rows[i]).find(selector).get(0);
if (cb === undefined)
break;
if ($(cb).is(':enabled'))
cb.checked = sender.checked;
}
}
So it will search each subsequent row for a checkbox with the name starting with "S_". Only the checkboxes the user has rights to will be changed. I was going to use $(td).index() to find the right column, but this didn't work out because some rows had colspan's greater than 1.

how to find the next td element type using jquery

<tr>
<td class="value" style="width:40%;">
<label class="label">Gender value</label>
</td>
<td class="value" style="width:40%;">
<input id="checkbox" type="checkbox" tabindex="0" name="chkCustom">
<label>M</label>
<input id="checkbox" type="checkbox" tabindex="0" name="chkCustom">
<label>F</label>
<input id="checkbox" type="checkbox" tabindex="0" name="chkCustom">
<label>U</label>
</td>
</tr>
I have the above HTML, I am reading all the controls from my webpage dynamically. In above I want to read the label value to its specified type and read the next value on the basis of its type:
Please look on my code:
// Read labels text
$("#tblCustomFields tr .label").each(function () {
var value = this.innerHTML;
console.log(this);
var type = $(this).closest('td').next().find('input').val();
alert(value);
alert(type);
//If next element type is *checkbox* then read checkbox values
if(type == "checkbox")
{
// Read checkbox values
$('tblCustomFields tr input:checked').each(function (s) {
var inputCheckBox = new Array();
inputCheckBox.push([this.id, 0]);
});
for (var i = 0; i < inputCheckBox.length; i++) {
alert(inputCheckBox[i]);
}
}
});
The above code will give me all the checkboxes on the webpage but I want the checkboxes only defined in the above HTML, and I also want to read the values of only those checkboxes which are checked. Please help.
GOAL: I am binding the dynamic HTML to the page its type might be checkbox or dropdown or text. Now I want to read the page labels and the values related to that labels. For ex my label(Gender value) has values of type checkbox so I just want to read the checked checkbox values related to that label.
UPDATE: At least tell me that how can I get the next element type
I am using the below code:
var type = $(this).closest('td').next().find('type').val();
ANY HELP
I think that all the markup has to be reviewed, but anyway, I think I know (please notice me if don't) what you want.
Try this:
// Read labels text
$("#tblCustomFields tr .label").each(function () {
var value = this.innerHTML;
console.log(this);
alert(value);
var inputCheckBox = new Array();
$(this).first().closest("td").next().find("input[type='checkbox']:checked").each(function(){
inputCheckBox.push($(this).next("label").text());
});
for (var i = 0; i < inputCheckBox.length; i++) {
alert(inputCheckBox[i]);
}
});
I'll make you a jsFiddle to test it.
Your question is confusing.
$("#tblCustomFields tr .label") - This will look for a child of TR with class label. Your HTML, shows that this resides inside td. If all the label elements have class label, you can refer each by -
$(".label).each(function(){
//do whatever you want
});
To get the element type next to the label with class label -
$(".label).each(function(){
var NextTd = $(this).parent().next(); // refers to the next td
$(NextTd).each(function(){
var type = $(this).find('input').prop('tagName');
//do whatever you want
});
});

On click button a validation on checkbox if user selects more than one checkbox, it should allow if user selects only one checkbox

On a button click JavaScript Validation should be: If a user select one checkbox it should allow to process further to any script, but when user selects more than one checkbox it should prompt that "you can select only one check box"
I am not getting to What javaScript I should write ?
<tr><td colspan='2'><input type='checkbox' name='check1' value=12> Q.12 Torronto in located in ?</td></tr>
<tr><td colspan='2'><input type='checkbox' name='check1' value=4> Q.4 Columbo is the capital of which country ?</td></tr>
<tr><td colspan='2'><input type='checkbox' name='check1' value=16> Q.16 Most used social suite ?</td></tr>
<tr><td colspan='2'><input type='checkbox' name='check1' value=19> Q.19 Largest State ?</td></tr>
Function call
<td><input type='submit' type='Edit' value='EDIT' formmethod='post' formaction='/~xyz/cgi-bin/Project/CheckEdit.py' onclick='return(CheckedOne())'></td></tr>
The JS which I tried:
function Checked() {
var d = document.myForm.check1;
var arr = 0;
for (var i = 0; i < d.length; i++) {
if (d[i].checked) {
arr++;
alert(arr);
}
}
if (arr == 1) return true;
else {
alert("Please select only one Checkbox");
return false;
}
}
I think you can do better using the approach by sravis using jQuery.
Here are the issues in your original code:
You call the function CheckedOne in the HTML but have a different name in the JS (Checked).
Also, use document.getElementsByName('check1'); to get the
array.
See http://jsbin.com/iTiQOFIX/1/
jQuery length will get you total checked boxes
http://jsfiddle.net/yAz2j/
$(".subtn").live('click', function() {
var total = $('.check1:checked').length;
if(total > 1) {
alert(" Checked : "+total);
// your code
} else {
alert("Checked only one!");
}
return false;
});
Also check this post: https://stackoverflow.com/a/5594976/1570901

Categories

Resources