jQuery - Disabling checkbox & adding attribute on click - javascript

I need checkboxes + table rows that share attributes to be enabled once the first checkbox has been ticked. (id for the table row + class for checkbox).
This is only half working
My problem is that if you have multiple boxes selected and uncheck just one, all of the checkboxes and table rows lose the disabled attribute.
https://jsfiddle.net/a1p7an7o/
HTML
<tr id="IN-HOUSE">
<input onchange="check();" class="IN-HOUSE" name="bill[]" type="checkbox">
<label for="Bill?">Bill?</label>
</td>
</tr>
Javascript
<script>
function check(){
$('input[name*=bill]').change(function() {
$t = $(this);
var $th = $(this).attr('class');
$c = $("tr[id!='"+$th+"']");
if ($(this).is(':checked')) {
$('input[name*=bill]').each(function() {
if ($(this).attr('class') != $th) {
$(this).not($t).prop('disabled', true);
$c.not($t).addClass( "disable" );
}
});
} else {
$('input[name*=bill]').each(function() {
if ($(this).attr('class') != $th) {
$(this).not($t).prop('disabled', false);
$("tr[id!='"+$th+"']").removeClass("disable");
}
});
}
});
}
</script>

Related

How to keep selected Radio button value after saved in jQuery

I have dynamic radio buttons in VBTML page and jQuery. I have 3 radio buttons and when i am selecting first/second radio button and click on save. The selected Radio button text is correctly saving into database. But in frontend it is not selecting the saved Radio button text. Always it is selecting last Radio button. Please see my code in below. Please help me how to keep checked the selected radio button option.
<table>
<tr>
<td>
#Code
For Each item In Model.StudentCourseLookup
Dim itemName = item.Text
#<input type="radio" name="CourseDetails" id="#itemName" class="cbxStudentCourse" />
#<span>#item.Text</span>
#<br />
Next
End Code
#Html.TextBoxFor(Function(m) m.StudentCourse, New With {.style = "display: none;"})
</td>
</tr>
</table>
<script type="text/javascript">
if ($("#StudentCourse").val !== '') {
var data1 = $("#StudentCourse").val();
$.each(data1.split('|'), function (_, val) {
if (val.length > 1) {
$(':input[name="CourseDetails"]').prop('checked', true);
}
});
}
function OStudentCourseSave() {
var studentCourseList = ''
$('.cbxStudentCourse').each(function (index, cbx) {
if (this.checked === true) {
studentCourseList = cbx.id;
}
});
$("#StudentCourse").val(studentCourseList);
var sc= #Html.Raw(Json.Encode(Model)); //Getting model
sc.StudentCourse = $("#StudentCourse").val();
}
</Script>
The following piece of code is the problem:
if (val.length > 1) {
$(':input[name="CourseDetails"]').prop('checked', true);
}
Since all the radio buttons have the same name you need to make it a bit more explicit and start using id's since this is what you're gathering anyway.
Try updating it to something like this to see if it helps:
$(':input[id="' + val + '"]').prop('checked', true);
Or even:
$('#' + val).prop('checked', true);

checked all/ unchecked all but limit row for check

I have
<thead>
<tr>
<th>Num</th>
<th>name</th>
<th>date</th>
<th><input type="checkbox" name="m_check" id="m_check" /></th>
</tr>
</thead>
<tbody>
<!-- i have loop for get data -->
<tr>
<td>$Num</td>
<td>$name</td>
<td>$date</td>
<td><input type="checkbox" name="e_check[]" value="<?php echo $companys->data[$i]['com_id'] ?>" class ="e_check" id="e_check_<?php echo $companys->data[$i]['com_id'] ?>" /></td>
</tr>
<!-- end loop for get data -->
</tbody>
this is my script
$('#m_check').change('change',function() {
if ($(this).is(':checked')) {
$('input[name="e_check[]"]:checkbox').attr('checked', true);
$('#ib_email').removeAttr("disabled");
} else {
$('input[name="e_check[]"]:checkbox').attr('checked', false);
$('#ib_email').attr("disabled", "disabled");
}
});
my problem is i need when user checked on m_check it's check element of e_check but check only 10, if my e_check more than 10 also.
please help me to correct my js
I also see this but i still can not custom my code :(
**Confirm my code is not wrong for user checked all, it's checked element row all, unchecked and it's unchecked all element row but i need when user checked all button it's checked element row limit 10 row top and other is still not check
There are a few mistakes in the jQuery. Prop should be used instead of attributes for the checked prop. Also ':checkbox' is not necessary when name="e_check[]" is already a unique identifier. Lastly, checkout the snippet at the bottom to grab the number. With it, you can set the checking behavior to reflect the number grabbed.
$('#m_check').change('change', function () {
if ($(this).is(':checked')) {
$('[name="e_check[]"]').prop('checked', true);
$('#ib_email').removeAttr("disabled");
} else {
$('[name="e_check[]"]').prop('checked', false);
$('#ib_email').attr("disabled", "disabled");
}
var $num = $(this).closest('table').find('td:first');
$num = parseInt($num);
});
You should do it like
$(document).on('change', '#m_check', function() {
$('#m_check').click(function () {
if ($(this).is(':checked')) {
$('input[type=checkbox].e_check').map(function (_, el) {
$(el).prop('checked', true);
});
} else {
$('input[type=checkbox].e_check').map(function (_, el) {
$(el).prop('checked', false);
});
}
});
});
or
$('#m_check').change(function() {
});
Edited:
Now when you will click on <input type="checkbox" name="m_check" id="m_check" /> All of your records will be checked.
you can do in this way.
I am assuming there is class tablecheckbox attachewd to tbody to
uniquely identify the checkbox.
$('#m_check').on('change',function() {
if ($(this).is(':checked')) {
if( $(".tablecheckbox tr input[type='checkbox']").length > 10){
$(".tablecheckbox tr input[type='checkbox']").slice(0,10).prop('checked',true)
}else{
$(".tablecheckbox tr input[type='checkbox']").prop('checked',true)
}
$('#ib_email').removeAttr("disabled");
} else {
$(".tablecheckbox tr input[type='checkbox']").slice(0,10).prop('checked',false)
$('#ib_email').attr("disabled", "disabled");
}
});

How to uncheck a checkbox when checked option is other than 'All'

I've multiple checkboxes which are populated from database, except one checkbox which is "All" (used to check/uncheck all other checkboxes onclick)
When all the options are checked and if any option other than 'All' is unchecked then checkbox of All should be unchecked.
When all the option are checked except 'All' then 'All' should be checked. How to proceed?
My code:
<script>
$(document).ready(function () {
('#check').append('<input type="checkbox" id="checkAll" name="myCheckbox[]" value="All" > </input>' + "All" );
//'datadb' is data from db in json array
//datadb={'apple','banana','orange'}
$.each(datadb, function(i, fruit) {
$('#check').append('<input type="checkbox" name="myCheckbox[]" class=".chk" value="' + fruit + '" > </input>' + fruit );
$('#check').append('<br/>');
}
});
</script>
<script>
$(document).ready(function() {
$("#checkAll").click(function () {
$('input:checkbox').not(this).removeProp('checked');
});
});
</script>
<div id="check" onchange="testingclick()"></div>
How to fill the function to satisfy above 1 and 2
<script>
function testingclick(){
var $check_values = $("input[type=checkbox][name='myCheckbox[]']:checked");
var $check_len = $check_values.length;
var $total_len = $("input[type=checkbox][name='myCheckbox[]']").length;
window.var_multiple_checked = $check_values.map(function(){ return "'" + this.value + "'"; }).get();
temp_checked= window.var_multiple_checked;
}
</script>
For this code.
$('input:checkbox').not(this).prop('checked', this.checked);
Try to use removeProp instead
$('input:checkbox').not(this).removeProp('checked');
And for the events of your checkbox. Hook all with event.
$(document).ready(function() {
$('input:checkbox').click(function () {
if ($(this).attr('id') === 'checkAll' && $(this).is(':checked')) {
$('input:checkbox').not($(this)).removeProp('checked');
} else {
$('#checkAll').removeProp('checked');
}
});
});

How to check the Select all checkbox after checking all its child checkboxes?

I want to check all the checkboxes upon checking the "Selectall" checkbox and vice versa if I select all the checkboxes one by one then the "Selectall" checkbox should be automatically get checked. If I uncheck any of it's child checkboxes then the "Select all" checkbox should also be unchecked.
In my code, all the things are working except one thing that
if I select all the checkboxes one by one then the "Selectall" checkbox should be automatically get checked. Can anyone help me in making this thing workable for me. For your reference I'm giving my file code (HTML and Javascript code) here, so that you could test on your local machine.:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function () {
$("#ckbCheckAll").click(function () {
$(".checkBoxClass").prop('checked', $(this).prop('checked'));
});
$(".checkBoxClass").change(function(){
if (!$(this).prop("checked")){
$("#ckbCheckAll").prop("checked",false);
}
});
});
</script>
</head>
<body>
<input type="checkbox" id="ckbCheckAll" /> Check All
<p id="checkBoxes">
<input type="checkbox" class="checkBoxClass" id="Checkbox1" />
<br />
<input type="checkbox" class="checkBoxClass" id="Checkbox2" />
<br />
<input type="checkbox" class="checkBoxClass" id="Checkbox3" />
<br />
<input type="checkbox" class="checkBoxClass" id="Checkbox4" />
<br />
<input type="checkbox" class="checkBoxClass" id="Checkbox5" />
<br />
</p>
</body>
</html>
You can check how many checkboxes are there and how many are checked:
$(".checkBoxClass").change(function(){
var all = $('.checkBoxClass');
if (all.length === all.filter(':checked').length) {
$("#ckbCheckAll").prop("checked", true);
} else {
$("#ckbCheckAll").prop("checked", false);
}
});
Not sure if all can be just $(this);
In addition to the selectAll checkbox I have experimented with adding selectRow and selectCol checkboxes to get the same effect for each row and column of the grid of checkboxes.
see http://jsfiddle.net/wf_bitplan_com/snpc2L34/29/
/**
* http://stackoverflow.com/questions/432493/how-do-you-access-the-matched-groups-in-a-javascript-regular-
* expression
* examples:
*
* var matches = getRegexMatches(/(dog)/, "dog boat, cat car dog");
* console.log(matches);
*
* var matches = getRegexMatches(/(dog|cat) (boat|car)/, "dog boat, cat car");
* console.log(matches);
*/
function getRegexMatches(regex, string) {
if(!(regex instanceof RegExp)) {
return "ERROR";
}
else {
if (!regex.global) {
// If global flag not set, create new one.
var flags = "g";
if (regex.ignoreCase) flags += "i";
if (regex.multiline) flags += "m";
if (regex.sticky) flags += "y";
regex = RegExp(regex.source, flags);
}
}
var matches = [];
var match = regex.exec(string);
while (match) {
if (match.length > 2) {
var group_matches = [];
for (var i = 1; i < match.length; i++) {
group_matches.push(match[i]);
}
matches.push(group_matches);
}
else {
matches.push(match[1]);
}
match = regex.exec(string);
}
return matches;
}
/**
* get the select_row or select_col checkboxes dependening on the selectType row/col
*/
function getSelectCheckboxes(selectType) {
var regex=new RegExp("select_"+selectType+"_");
var result= $('input').filter(function() {return this.id.match(regex);});
return result;
}
/**
* matrix selection logic
* the goal is to provide select all / select row x / select col x
* checkboxes that will allow to
* select all: select all grid elements
* select row: select the grid elements in the given row
* select col: select the grid elements in the given col
*
* There is a naming convention for the ids and css style classes of the the selectors and elements:
* select all -> id: selectall
* select row -> id: select_row_row e.g. select_row_2
* select col -> id: select_col_col e.g. select_col_3
* grid element -> class checkBoxClass col_col row_row e.g. checkBoxClass row_2 col_3
*/
$(document).ready(function () {
// handle click event for Select all check box
$("#selectall").click(function () {
// set the checked property of all grid elements to be the same as
// the state of the SelectAll check box
var state=$("#selectall").prop('checked');
$(".checkBoxClass").prop('checked', state);
getSelectCheckboxes('row').prop('checked', state);
getSelectCheckboxes('col').prop('checked', state);
});
// handle clicks within the grid
$(".checkBoxClass").on( "click", function() {
// get the list of grid checkbox elements
// all checkboxes
var all = $('.checkBoxClass');
// all select row check boxes
var rows = getSelectCheckboxes('row');
// all select columnn check boxes
var cols = getSelectCheckboxes('col');
// console.log("rows: "+rows.length+", cols:"+cols.length+" total: "+all.length);
// get the total number of checkboxes in the grid
var allLen=all.length;
// get the number of checkboxes in the checked state
var filterLen=all.filter(':checked').length;
// console.log(allLen+"-"+filterLen);
// if all checkboxes are in the checked state
// set the state of the selectAll checkbox to checked to be able
// to deselect all at once, otherwise set it to unchecked to be able to select all at once
if (allLen == filterLen) {
$("#selectall").prop("checked", true);
} else {
$("#selectall").prop("checked", false);
}
// now check the completeness of the rows
for (row = 0; row < rows.length; row++) {
var rowall=$('.row_'+row);
var rowchecked=rowall.filter(':checked');
if (rowall.length == rowchecked.length) {
$("#select_row_"+row).prop("checked", true);
} else {
$("#select_row_"+row).prop("checked", false);
}
}
});
$('input')
.filter(function() {
return this.id.match(/select_row_|select_col_/);
}).on( "click", function() {
var matchRowColArr=getRegexMatches(/select_(row|col)_([0-9]+)/,this.id);
var matchRowCol=matchRowColArr[0];
// console.log(matchRowCol);
if (matchRowCol.length==2) {
var selectType=matchRowCol[0]; // e.g. row
var selectIndex=matchRowCol[1]; // e.g. 2
// console.log(this.id+" clicked to select "+selectType+" "+selectIndex);
// e.g. .row_2
$("."+selectType+"_"+selectIndex)
.prop('checked', $("#select_"+selectType+"_"+selectIndex).prop('checked'));
}
});
});
Use jQuery( ":checkbox" )
Maybe you can look # selectors of jquery http://api.jquery.com/category/selectors/
//----------Select AllCheckBoxes Begin ------------------------
function toggleChkBox() {
$('#tblPermissionDetails td input:checkbox').prop('checked', $('#chkSelectAll')[0].checked);
}
//----------Select AllCheckBoxes End --------------------------
//----------Check/Uncheck SelectAll checkbox based on other checkboxes Begin----------------
$('#tblPermissionDetails td input:checkbox').change(function() {
if (!$(this).prop("checked")) {
$("#chkSelectAll").prop("checked", false);
} else {
var PermissionList = [];
var PermissionListChecked = [];
$('#tblPermissionDetails td input:checkbox').each(function() {
PermissionList.push(this.name);
})
$('#tblPermissionDetails td input:checkbox:checked').each(function() {
PermissionListChecked.push(this.name);
})
if (PermissionList.length == PermissionListChecked.length) {
$("#chkSelectAll").prop("checked", true);
}
}
});
//----------Check/Uncheck SelectAll checkbox based on other checkboxes End------------------
<table class="table table-striped" id="tblPermissionDetails">
<thead>
<tr>
<th>Sl.No</th>
<th>Permission</th>
<th>Description</th>
<th><input type="checkbox" id="chkSelectAll" onclick="toggleChkBox();" />(Select All)</th>
</tr>
</thead>
<tbody>
#{ int i = 1; List
<FDSApp.Models.RolePermissionDetailsModel> permissionModel = Model; foreach (var item in permissionModel) {
<tr>
<td>#i</td>
<td>#item.PermissionName</td>
<td>#item.Description</td>
<td>#Html.CheckBox(#item.PermissionId.ToString(), #item.IsEnabled == 0 ? false : true)</td>
</tr>
i = i + 1; } }
</tbody>
</table>

jQuery help with checking parent of checked child checkbox

I have a main row and some other rows underneath that main row like this:
[checkbox] Main heading row
[checkbox] first child row
[checkbox] second child row
When I click on the child row, it should check the parent (main) row automatically. Problem is that it doesn't check it first time I click it. I have to check the first child row first, then uncheck the first child row and then check first child row again to get the parent (main) row get checked. I want the parent row get checked as soon as any of the child rows get checked.
I am using the following code
function checkbox_click(){
var n = event.srcElement;
if(n.parentElement.id == "row"){
n = n.parentElement;
}
if(n.id == "row"){
alert("ID: 1");
n.rs = n.parentElement;
if(this.multiSelect == 0){ // single select
alert("ID: 2");
n.all[0].checked = 1;
this.selectedRows = [ n ];
if(this.lastClicked && this.lastClicked != n){
this.lastClicked.all[0].checked = 0;
this.lastClicked.style.color = "000099";
this.lastClicked.style.backgroundColor = "";
}
} else {
alert("ID: 3");
n.all[0].click();
}
if(this.parentElement == pg.procs) {
alert("ID: 4");
var terminate = false;
var counter = 0;
if(n.className == "proc") {
alert("ID: 5");
z = n.nextSibling;
while(z.id == "row" && z.className != "proc" && !terminate) {
alert("ID: 6");
z.all[0].checked = 0;
z.style.backgroundColor = z.className == "w" ? "ffffff" : "ffffcc";
counter++;
if(counter > 1000) terminate = true;
z = z.nextSibling;
}
} else {
$(".row input").change(function() {
alert("ID: 7");
var $row= $(this).closest(".row");
var $main_row = $row.prev('.proc').length ? $row.prev('.proc') : $row.prevUntil(".proc").prev();
$main_row.find(":checkbox").attr("checked", function(i,attr) {
return $main_row.nextUntil('.proc').filter(':has(input:checked)').length ? "checked" : false;
});
});
$(".proc input").change(function() {
alert("ID: 8");
$(this).closest(".proc").nextUntil('.proc').children(':checkbox').attr('checked', this.checked);
});
}
If you want to check the parent checkbox when one of the child checkboxes is checked, I would suggest using a common class for the child checkboxes, and a unique id attribute for the parent checkbox (or store it as a variable).
Let's assume you have a structured HTML document that contains something like the following:
<div>
<input type="checkbox" name="ckparent" id="ckparent" />
<label for="ckparent">Parent</label>
<div>
<input type="checkbox" name="ckchild1" id="ckchild1" class="ckchild" />
<label for="ckchild1">Child 1</label>
</div>
<div>
<input type="checkbox" name="ckchild2" id="ckchild2" class="ckchild" />
<label for="ckchild2">Child 2</label>
</div>
</div>
You could then write the following jQuery code to check the parent checkbox when either of the children are checked:
$('input:checkbox.ckchild').click(function(event) {
var checked = $(this).is(':checked');
if (checked) {
$('#ckparent').attr('checked', true);
}
});
EDIT: The order in which the changed and clicked events are fired with regards to when the checked attribute is actually changed is dependent on the browser you are using -- which browsers are you targeting?

Categories