javascript to disable/enable checkbox and dropdown menu - javascript

Hi I am trying to disable a drop down when a checkbox is checked and the when the checkbox is unchecked enable the drop down. below is my javascript and it is working when I check the checkbox but it won't let me uncheck the checkbox:
<script type="text/javascript">
function test(obj){
if (document.getElementsByName("aForm[0].info")[0].checked = true) {
alert("here");
document.getElementsByName("aForm[0].gender")[0].disabled = true;
}
else document.getElementsByName("aForm[0].info")[0].checked = false;{
document.getElementsByName("aForm[0].gender")[0].enabled = true;
}
}
</script>
and here is my jsp
<logic:iterate id="data" name="aForm" property="testList">
<tr>
<td>
<html:checkbox indexed="true" name="aForm" styleId="something" property="info" onclick="test(this)"/>
</td>
<td>
<html:select name="aForm" indexed="true" property="unit" styleId="dropdown">
<html:optionsCollection name="aForm" property="selectGender" value="value" label="label"/>
</html:select>
>
</td>
</tr>
</logic:iterate>

You are storing a value, not comparing
The if statement
if( document.getElementsByName("aForm[0].info")[0].checked = true )
should be
if( document.getElementsByName("aForm[0].info")[0].checked == true )
notice the ==
And what is with the else?
else document.getElementsByName("aForm[0].info")[0].checked = false;{
You are treating it like an else if(), else does not have a statement there.
Your code should throw JavaScript errors when run.
And there is no such thing as enabled, it is just disabled, true/false.
Your code should look like
function test(obj) {
if (document.getElementsByName("aForm[0].info")[0].checked = true) {
document.getElementsByName("aForm[0].gender")[0].disabled = true;
}
else {
document.getElementsByName("aForm[0].gender")[0].disabled= false;
}
}
and it can be simplified down to just 3 lines:
function test(obj) {
document.getElementsByName("aForm[0].gender")[0].disabled = document.getElementsByName("aForm[0].info")[0].checked;
}
and to make it work without the element names:
<script>
function test(cb){
cb.parentNode.parentNode.getElementsByTagName("select")[0].disabled = cb.checked;
}
</script>
<table>
<tbody>
<tr>
<td><input type="checkbox" onclick="test(this);"></td>
<td><select><option>a</option><option>b</option></select></td>
</tr>
<tr>
<td><input type="checkbox" onclick="test(this);"></td>
<td><select><option>a</option><option>b</option></select></td>
</tr>
</tbody>
</table>
Note: parentNode.parentNode is bound to break if the page structure changes. :)

Related

How do I select all check box when I click on Select button using jQuery

I have HTML page which have multiple check boxes and individually they can be checked. I have button select, so what I am suppose to do is. When I click on select all the check boxes should get selected, and deselected.
Html
<html>
<head>
<script src="jquery.js"></script>
</head>
<body>
<script>
$(document).ready(function() {
$('#selectAll').click(function(event) { //on click
if(this.checked) { // check select status
$('.btn-chk').each(function() { //loop through each checkbox
this.checked = true; //select all checkboxes with class "checkbox1"
});
}else{
$('.btn-chk').each(function() { //loop through each checkbox
this.checked = false; //deselect all checkboxes with class "checkbox1"
});
}
});
});
</script>
<table id="example" cellspacing="0" width="20%">
<thead>
<tr>
<th><button type="button" id="selectAll" class="myClass">Select</button></th>
<th>number</th>
<th>company</th>
<th> Type</th>
<th> Address</th>
<th>Code</th>
</tr>
</thead>
<tbody>
<tr>
<td><span class="button-checkbox">
<button type="button" class="btn-chk" data-color="success"></button>
<input type="checkbox" class="hidden" />
</span>
</td>
<td>1</td>
<td>APPLE</td>
<td>IT</td>
<td>San Jones</td>
<td>US</td>
</tr>
<tr>
<td><span class="button-checkbox">
<button type="button" class="btn-chk" data-color="success"></button>
<input type="checkbox" class="hidden" />
</span>
</td>
<td>2</td>
<td>DELL</td>
<td>IT</td>
<td>San Jones</td>
<td>US</td>
</tr>
<tr>
<td><span class="button-checkbox">
<button type="button" class="btn-chk" data-color="success"></button>
<input type="checkbox" class="hidden" />
</span>
</td>
<td>3</td>
<td>Amazon</td>
<td>IT</td>
<td>San Jones</td>
<td>US</td>
</tr>
<tr>
<td><span class="button-checkbox">
<button type="button" class="btn-chk" data-color="success"></button>
<input type="checkbox" class="hidden" />
</span>
</td>
<td>4</td>
<td>Microsoft</td>
<td>IT</td>
<td>San Jones</td>
<td>US</td>
</tr>
</tbody>
</body>
</html>
Output
In the image I have select button. what I want is when I click on select button all the check boxes should get selected
If you want to toggle the checkbox state, you can do like this
var chkd = true;
$('#selectAll').click(function(event) {
$(":checkbox").prop("checked", chkd);
chkd = !chkd;
});
Fiddle
#selectAll is a button, it doesn't have a checked property, but one could emulate that with a data attribute instead.
Secondly, .btn-chk isn't a checkbox either, so it can't be checked, you have to target the checkboxes
$(document).ready(function() {
$('#selectAll').click(function(event) {
var checked = !$(this).data('checked');
$('.btn-chk').next().prop('checked', checked);
$(this).data('checked', checked);
});
});
FIDDLE
An simple way is like below:
$(function() {
$('#selectAll').click(function() {
$(':checkbox').prop('checked', !$(':checkbox').prop('checked'));
});
});
The Demo.
Check this jsFiddle
$(document).ready(function() {
$('#selectAll').click(function() {
$(':checkbox').prop('checked', !$(':checkbox').prop('checked'));
});
});
You can simply use it
For more info on jQuery visit w3schools-jquery
Change your jQuery code to
$('#selectAll').click(function(event) { //on click
if($('.hidden').prop('checked') == false) { // check select status
$('.hidden').each(function() { //loop through each checkbox
this.checked = true; //select all checkboxes with class "checkbox1"
});
}else{
$('.hidden').each(function() { //loop through each checkbox
this.checked = false; //deselect all checkboxes with class "checkbox1"
});
}
});
This will toggle between checked and unchecked of the checkboxes when you click the button.
inside the "click" function "this" is button and not a checkbox. and button property checked is underfined.
"$('.btn-chk').each" - is loop on each element with class ".btn-chk", in your HTML is buttons and not an checkboxes.
in your context the "#selectAll" must be a checkbox and put class '.btn-chk' on your checkboxes
Try this-
var checked = true;
$('#selectAll').click(function(event) {
$('table tr').each(function( index ) {
$(this).find('input[type="checkbox"]').prop(checked, true);
});
checked = !checked;
});
You can do it like this also with ':checkbox' selector.
$(document).ready(function () {
$('#selectAll').on('click', function () {
$(':checkbox').each(function () {
$(this).click();
});
});
});
This will definitely works.
$("#selectAll").click(function(){
var checked = !$(this).data('checked');
$('.btn-chk').prop('checked', checked);
$(this).data('checked', checked);
});

jQuery - Color table rows when checkbox is checked and remove when not

I'm a little stuck, can't get my head around this problem. I have setup some jQuery that identifies the values in radio inputs, which align with values within the table. This is the start to doing some filtering on a table.
I want the following three things to happen:
Whenever you click on a filter and the cell has the same value, it's row gets highlighted
Whenever you check that option off, it gets removed
If the page loads and an option is already checked, the row gets highlighted on load
jQuery Code:
$(function () {
// On Change of Radio Buttons
$('input').on('change', function () {
var filter = $('input:checkbox[name=filter]:checked').val();
// Edit the Rows
$(".gameStatus").filter(function () {
return $(this).text() == filter;
}).parent('tr').addClass('filtered');
});
});
jsfiddle:
http://jsfiddle.net/darcyvoutt/8xgd51mg/
$(function () {
var filters = [];
var edit_rows = function () {
filters = [];
$('input:checkbox[name=filter]:checked').each(function () {
filters.push(this.value);
});
// Edit the Rows
$(".gameStatus").each(function () {
$(this).parent('tr')
.toggleClass('filtered',
filters.indexOf($(this).text()) > -1
);
});
}
edit_rows();
// On Change of Radio Buttons
$('input').on('change', edit_rows);
});
jsfiddle
edit: added functionality so it gets invoked on page load
Here's alternate solution ...
$(function () {
function highlight() {
var filter = $(this).val();
var checked = this.checked;
// Edit the Rows
var affectedRows = $(".gameStatus").filter(function () {
return $(this).text() == filter;
});
if (checked) {
affectedRows.parent('tr').addClass('filtered');
} else {
affectedRows.parent('tr').removeClass('filtered');
}
}
$('input').each(highlight);
// On Change of Radio Buttons
$('input').on('change', highlight);
});
.filtered {
background: tomato;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="content">
<div class="filters">
<input type="checkbox" name="filter" id="draft" value="Draft" checked />
<label for="draft">Draft</label>
<input type="checkbox" name="filter" id="active" value="Active" />
<label for="active">Active</label>
<input type="checkbox" name="filter" id="complete" value="Complete" />
<label for="complete">Complete</label>
<input type="checkbox" name="filter" id="acrhived" value="Archived" />
<label for="acrhived">Archived</label>
</div>
<table id="userManager">
<tbody>
<tr>
<th>Game</th>
<th>Teams</th>
<th>Status</th>
</tr>
<tr>
<td>Another Game</td>
<td>New Team, Project Lucrum</td>
<td class="gameStatus">Active</td>
</tr>
<tr>
<td>New Game</td>
<td>No teams selected</td>
<td class="gameStatus">Draft</td>
</tr>
<tr>
<td>New Game</td>
<td>New Team, Just in Case</td>
<td class="gameStatus">Active</td>
</tr>
</tbody>
</table>
<div class="test"></div>
</div>
try this. :)
$(function () {
var highlight = function(el){
if(el.is(':checked')){
$(".gameStatus:contains("+el.val()+")")
.parent('tr').addClass('filtered');
}else{
$(".gameStatus:contains("+el.val()+")")
.parent('tr').removeClass('filtered');
}
}
//On Load
highlight($('input[type="checkbox"][name=filter]:checked'));
// On Change of Radio Buttons
$('input').on('change', function () {
highlight($(this));
});
});

how to get a value in a list on a checkboxlist control and use it to validate

I have a form in asp.net 3.5 , which has a master page and a child page (content page). The form has several questions, I am using the asp.net checkboxlist for a questions, since multiple options can be selected, if the user selects 'Other' on one of the selections, then they have to enter data into a textbox field.
I made the following client side javascript to validate this but, the code doesnt seem to check wheter the Other option value is selected, I believe it has to do with the way the html is rendered on the page,,,
Can you please suggest how to do this?
Thanks in advance.
Rendered Javascript
//Here I am trying to get the text property of the label rendered for the texbox
// and set my validation arguments
<script language='javascript' type='text/javascript'>
function checkOther2(oSrc, args) {
{
var elementRef =
document.getElementById('ctl00_Content_CheckBoxList1');
var checkBoxArray = elementRef.getElementsByTagName('input');
var checkedValues = '';
for (var i = 0; i < checkBoxArray.length; i++) {
var checkBoxRef = checkBoxArray[i];
if (checkBoxRef.checked == true) {
// You can only get the Text property, which
will be in an HTML label element.
var labelArray =
checkBoxRef.parentNode.getElementsByTagName('label');
if (labelArray.length > 0) {
if (checkedValues.length > 0)
checkedValues += ',';
checkedValues += labelArray[0].innerHTML.text;
if (checkedValues == 'Other') {
args.IsValid = !(args.Value == "")
// test
alert("Hello");
}
}
else {
args.IsValid = true;
}
}
}
}
}
// HTML Rendered
<tr>
<td style="height: 20px">
</td>
</tr>
<tr>
<td style="font-weight: 700">
2.- What did you like most about working here?<strong>
Check all that apply
<span id="ctl00_Content_CheckBoxListValidator1"
style="color:Red;display:none;"></span>
</strong><br /> </td>
</tr>
<tr>
<td>
<table id="ctl00_Content_CheckBoxList1"
class="myradioButton" border="0">
<tr>
<td><input id="ctl00_Content_CheckBoxList1_0" type="checkbox"
name="ctl00$Content$CheckBoxList1$0" /><label
for="ctl00_Content_CheckBoxList1_0">Staff</label></td>
</tr><tr>
<td><input id="ctl00_Content_CheckBoxList1_1" type="checkbox"
name="ctl00$Content$CheckBoxList1$1" /><label
for="ctl00_Content_CheckBoxList1_1">Facility</label></td>
</tr><tr>
<td><input id="ctl00_Content_CheckBoxList1_2" type="checkbox"
name="ctl00$Content$CheckBoxList1$2" /><label
for="ctl00_Content_CheckBoxList1_2">Pay</label></td>
</tr><tr>
<td><input id="ctl00_Content_CheckBoxList1_3" type="checkbox"
name="ctl00$Content$CheckBoxList1$3" /><label
for="ctl00_Content_CheckBoxList1_3">Other</label></td>
</tr>
</table>
</td>
</tr>
<tr>
<td>
If other, please elaborate:<br />
<input name="ctl00$Content$txt2other"
type="text" id="ctl00_Content_txt2other" class="txtOther" />
<span id="ctl00_Content_CustomValidator3"
style="color:Red;font-weight:700;visibility:hidden;">Please enter a
comment in question #2.</span>
</td>
</tr>
<tr>
<td>
</td>
</tr>
<tr>
<td style="font-weight: 700">
2.- What did you like most about working here?<strong>
Check all that apply
<cc1:CheckBoxListValidator
ID="CheckBoxListValidator1" runat="server"
ControlToValidate="CheckBoxList1" Display="None"
ErrorMessage="Question 2 is
Required"></cc1:CheckBoxListValidator>
</strong><br /> </td>
</tr>
<tr>
<td>
----------- Actual Markup on asp.net form
<asp:CheckBoxList ID="CheckBoxList1"
runat="server" CssClass="myradioButton">
<asp:ListItem Text="Staff"
Value="Staff">Staff</asp:ListItem>
<asp:ListItem Text="Facility"
Value="Facility">Facility</asp:ListItem>
<asp:ListItem Text="Pay"
Value="Pay">Pay</asp:ListItem>
<asp:ListItem Text="Other"
Value="Other">Other</asp:ListItem>
</asp:CheckBoxList>
</td>
</tr>
<tr>
<td>
If other, please elaborate:<br />
<asp:TextBox ID="txt2other" runat="server"
CssClass="txtOther"></asp:TextBox>
<asp:CustomValidator
ID="CustomValidator3" runat="server"
ClientValidationFunction="checkOther2"
ControlToValidate="txt2other"
ErrorMessage="Please enter a comment in
question #2." style="font-weight: 700"
ValidateEmptyText="True"></asp:CustomValidator>
</td>
</tr>
Your JS looks rather complicated. Try a more simple approach...
function isValid(f)
{
var cb = document.getElementById('<%=CheckBoxList1_3.ClientID%>');
if(cb && cb.checked)
{
var tb = document.ElementById('<%=txt2other.ClientID%>');
if(tb && tb.value.length > 0)
{
f.submit();
}
else
{
alert('Please enter a comment in question #2.');
}
}
}
If you have a lot of these, try setting a property on the checkbox like value=other so when you loop through your checkboxes, you can use if(cb.checked && cb.value == 'other')

click anywhere on a table row and it will check the checkbox its in...?

I'm trying to figure out how to do this, but I can't find it out. Basically I want to be able to click anywhere on a table row and it will check/ unchecked the checkbox its in. I know it's possible because that's what PHPMyAdmin does...
here is my table row
<tbody>
<tr id="1" onclick="selectRow(1)"><td width="20px"><input type="checkbox" id="1" name="1/"></td><td>1</td><td>2011-04-21 22:04:56</td><td>action</td></tr>
<tr id="2" onclick="selectRow(2)"><td width="20px"><input type="checkbox" id="2" name="2/"></td><td>2</td><td>2011-04-21 22:04:56</td><td>action</td></tr>
</tbody>
<script type="text/javascript">
function selectRow(row)
{
var firstInput = row.getElementsByTagName('input')[0];
firstInput.checked = !firstInput.checked;
}
</script>
...
<tbody>
<tr onclick="selectRow(this)"><td width="20px"><input type="checkbox" id="chk1" name="chk1/"></td><td>1</td><td>2011-04-21 22:04:56</td><td>action</td></tr>
<tr onclick="selectRow(this)"><td width="20px"><input type="checkbox" id="chk2" name="chk2/"></td><td>2</td><td>2011-04-21 22:04:56</td><td>action</td></tr>
</tbody>
Note: You've also got collisions on ids. Your ids should be unique.
Here's an alternative with programmatic binding:
document.querySelector("table").addEventListener("click", ({target}) => {
// discard direct clicks on input elements
if (target.nodeName === "INPUT") return;
// get the nearest tr
const tr = target.closest("tr");
if (tr) {
// if it exists, get the first checkbox
const checkbox = tr.querySelector("input[type='checkbox']");
if (checkbox) {
// if it exists, toggle the checked property
checkbox.checked = !checkbox.checked;
}
}
});
<table>
<tbody>
<tr>
<td>
<input type="checkbox" id="chk1" name="chk1" />
</td>
<td>1</td>
<td>2011-04-21 22:04:56</td>
<td>action</td>
</tr>
<tr>
<td>
<input type="checkbox" id="chk2" name="chk2" />
</td>
<td>2</td>
<td>2011-04-21 22:04:56</td>
<td>action</td>
</tr>
<tr>
<td>
<input type="checkbox" id="chk2" name="chk3" />
</td>
<td>2</td>
<td>2011-04-21 25:30:16</td>
<td>action</td>
</tr>
</tbody>
</table>
You don't need JavaScript for this:
td label {
display: block;
}
<td width="20px"><input type="checkbox" id="chk2" name="chk2/"></td><td><label for="chk2">2</label></td><td><label for="chk2">2011-04-21 22:04:56</label></td><td><label for="chk2">action</label></td>
Just labels and a little CSS.
Try this one out...
$("tr").click(function() {
var checkbox = $(this).find("input[type='checkbox']");
checkbox.attr('checked', !checkbox.attr('checked'));
});
http://jsfiddle.net/dVay8/
Since this question getting so many views and the accepted answer has a small issue.
The issue is when you click on the checkbox it won't change. Actually what happens is the checkbox toggles twice. Because of we clicked on the checkbox and the table row as well. So here is a proper solution with a fix.
$('tr').click(function(event){
var $target = $(event.target);
if(!$target.is('input:checkbox'))
{
$(this).find('input:checkbox').each(function() {
if(this.checked) this.checked = false;
else this.checked = true;
})
}
});
Good luck devs.

JavaScript +css - Change main category's checkbox css, if any items beneath it are checked

All,
I have the attached code snippet where a category checkbox is checked if all items underneath it are checked. How can I modify the code such that:
If any checkbox underneath any category is checked, the CSS Style of it's parent "Category" checkbox should look greyed out. (I do not want to disable the checkbox. Just look grey or any color through CSS). This will denote some items are checked if the category is collapsed.
If all items are checked underneath a category, then the checkbox doesn't have to look greyed out as it will be checked too.
All the existing code functionality should be maintained as it works great..
PS: Sorry for the HTML being a mess...
Any suggestions?
Thanks
<html>
<head>
<script src="http://www.google.com/jsapi"></script>
<script>
google.load("jquery", "1.3.2");
google.load("jqueryui", "1.7.2");
</script>
<script language="JavaScript">
function toggleTableRows()
{
$(document).ready(function() {
$('img.parent')
.css("cursor","pointer")
.toggle(
function() {
$(this).attr("title","Click to Expand")
$(this).attr("src","arrow_collapsed.gif");
$('tr').siblings('#child-'+this.id).toggle();
},
function() {
$(this).attr("title","Click to Collapse");
$(this).attr("src","arrow_expanded.gif");
$('tr').siblings('#child-'+this.id).toggle();
}
);
initCheckBoxes();
});
}
function toggleCheckboxes(current, form, field) {
$(document).ready(function() {
$("#"+ form +" :checkbox[name^='"+ field +"[']")
.attr("checked", current.checked);
});
}
function toggleParentCheckboxes(current, form) {
var checked = $("#"+ form +" :checkbox[name='"+ current.name +"']").length ==
$("#"+ form +" :checkbox[name='"+ current.name +"']:checked").length;
// replace '[anything]' with '' instead of just '[]'
$("#"+ form +" :checkbox[name='"+ current.name.replace(/\[[^\]]*\]/, "") +"']")
.attr("checked", checked);
}
function initCheckBoxes(form) {
$("#"+ form +" :checkbox:checked").each(function() {
if (this.name.match(/chk[0-9]\[.*\]/)) {
toggleParentCheckboxes(this, form);
}
});
}
</script>
<script language="JavaScript">toggleTableRows();</script>
<style type="text/css">tr.c1 {display: none;}</style>
</head>
<body>
<form name="frmDinnerMenu" id="frmDinnerMenu" method="POST" action="">
<table border=1>
<tr>
<td><img class="parent" id="0" src="arrow_collapsed.gif" title="Click to Expand">Category - Fruits</td>
<td><input type="checkbox" name="chk0" onclick="toggleCheckboxes(this, 'frmDinnerMenu', 'chk0');"/></td>
</tr>
<tr class="c1" id="child-0">
<td>Apple</td>
<td><input type="checkbox" value="true" name="chk0[]" onclick="toggleParentCheckboxes(this, 'frmDinnerMenu');"/></td>
</tr>
<tr class="c1" id="child-0">
<td>Banana</td>
<td><input type="checkbox" value="false" name="chk0[]" onclick="toggleParentCheckboxes(this, 'frmDinnerMenu');"/></td>
</tr>
<tr class="c1" id="child-0">
<td>Orange</td>
<td><input type="checkbox" checked value="true" name="chk0[]" onclick="toggleParentCheckboxes(this, 'frmDinnerMenu');"/></td>
</tr>
<tr>
<td><img class="parent" id="1" src="arrow_collapsed.gif" title="Click to Expand">Category - Vegetables</td>
<td><input type="checkbox" name="chk1" onclick="toggleCheckboxes(this, 'frmDinnerMenu', 'chk1');"/></td>
</tr>
<tr class="c1" id="child-1">
<td>Eggplant</td>
<td><input type="checkbox" value="true" name="chk1[]" onclick="toggleParentCheckboxes(this, 'frmDinnerMenu');"/></td>
</tr>
<tr class="c1" id="child-1">
<td>Tomato</td>
<td><input type="checkbox" value="false" name="chk1[]" onclick="toggleParentCheckboxes(this, 'frmDinnerMenu');"/></td>
</tr>
<tr class="c1" id="child-1">
<td>Cabbage</td>
<td><input type="checkbox" checked value="true" name="chk1[]" onclick="toggleParentCheckboxes(this, 'frmDinnerMenu');"/></td>
</tr>
</table>
</form>
</body>
</html>
Code looks familiar ;)
Include a CSS class similar to this one (add further styling if you need it)
.graymeout { background-color:#D8D8D8 }
Change toggleParentCheckboxes to this (some "optimizations" included. Refactored out common selector parts and removed a "double" selection by using filter)
function toggleParentCheckboxes(current, form) {
var selector1 = "#"+ form +" :checkbox[name='";
var selector2 = selector1 + current.name +"']";
var set = $(selector2);
var checked = set.length == set.filter(":checked").length;
// replace '[anything]' with '' instead of just '[]'
var ele = $(selector1 + current.name.replace(/\[[^\]]*\]/, "") +"']");
ele.attr("checked", checked);
if(!checked)
ele.addClass("graymeout")
else
ele.removeClass("graymeout");
ele=null; set=null; selector1=null; selector2=null;
}
If you change the call to initCheckBoxes in toggleTableRows to initCheckBoxes("frmDinnerMenu"); you will get the highlighting also on page load instead of just when first child is changed.
I had also used the same approach as mentioned by jitter. It works pretty well and in my opinion is the only option available since a tri-state check box is not available on a browser.

Categories

Resources