toggling a highlight on a checkbox click - javascript

For the following table:
<table id="a_grid">
<tr id="a_row">
<td>Choice A<input type="checkbox" id="a_box" class="box"></td>
<td>Reason:<input type="text" id="a_text" class="reason"></td>
</tr>
<tr id="b_row">
<td>Choice B<input type="checkbox" id="b_box" class="box"></td>
<td>Reason:<input type="text" id="b_text" class="reason"></td>
</tr>
</table>
I am trying to make it work such that when you click the checkbox, it toggles a 'control' class to its corresponding text box that has a specific color. Trying to identify by classes so I can scale the table.
What I've tried:
$(".box").change(function () {
$(".reason").toggleClass("control", false);
});

Your currently targeting all checkboxes with .reason, whereas you need to use the context that comes with the event, I.E. the checkbox itself. From there you can traverse up to the row, and down to the input.
.toggleClass() will always remove the class, because you pass false as the second parameter. You can then toggle the class based on the checkbox, using the .checked property:
$('.box').change(function(){
var $this = $(this);
$this.closest('tr').find('.reason')
.toggleClass('control', $this.prop('checked'));
});
JSFiddle

Related

Show/Hide more than one <table> with a checkbox

I want to show and hide several tables on one page with one button. Unfortunately my script can only show and hide one table at a time.
I have a page with a lot of queries. There are also text fields in a table. For a better overview, the tables with the text fields should only be displayed when the checkbox is ticked. The checkbox should not be clicked at the beginning.
function Displayer(n)
{
var check = document.getElementById('Section'+n);
if (check.style.display == 'none')
{
check.style.display='inline';
}
else
{
check.style.display='none';
}
}
<p><input type="checkbox" class="btnstylega" onClick="Displayer(99)" />Show Tables</p>
<table id="Section99" style="display:none;"> <td>
AAAAAAAAAAAAAA
</td></table>
<table id="Section99" style="display:none;"> <td>
BBBBBBBBBBBBBBB
</td></table><br>
I want to show and hide many tables without adjusting the tables by clicking on the checkbox.
An ID must be unique in a document. The tool to mark multiple elements as part of a group is a class.
Replace your id attributes with class attributes.
Then replace getElementById with getElementsByClassName (or querySelectorAll).
These methods return lists of nodes and not single elements, so loop over the result like an array and access the style property on each one in turn.
The attribute id must be unique in a document, you can use class instead. You can use querySelectorAll() to target all the elements having the class, then loop through them to set the style. You can toggle the class using classList.toggle() like the following way:
function Displayer()
{
var check = document.querySelectorAll('.Section99');
check.forEach(function(table){
table.classList.toggle('show');
});
}
.Section99{
display: none;
}
.show{
display: block;
}
<p><input type="checkbox" class="btnstylega" onClick="Displayer()" />Show Tables</p>
<table class="Section99" class="hide"> <td>
AAAAAAAAAAAAAA
</td></table>
<table class="Section99" class="hide"> <td>
BBBBBBBBBBBBBBB
</td></table><br>
Improvement: It will add the event handler and trigger the change on load where needed
Note the data-attribute on the checkbox
var chg = new Event('change');
document.querySelectorAll(".btnstylega").forEach(function(but) {
but.addEventListener("change", function() {
var checked = this.checked,
section = this.getAttribute("data-tables");
document.querySelectorAll('.Section' + section).forEach(function(sect) {
sect.classList.toggle("hide",!checked);
});
})
but.dispatchEvent(chg);
});
.hide {
display: none;
}
<p><input type="checkbox" class="btnstylega" data-tables="88" checked />Show Tables 88 </p>
<p><input type="checkbox" class="btnstylega" data-tables="99" />Show Tables 99</p>
<table class="Section88">
<tr>
<td>
AAAAAAAAAAAAAA
</td>
</tr>
</table>
<table class="Section88">
<tr>
<td>
BBBBBBBBBBBBBBB
</td>
</tr>
</table><hr>
<table class="Section99">
<tr>
<td>
CCCCCCCCCCCCCCCC
</td>
</tr>
</table>
<table class="Section99">
<tr>
<td>
DDDDDDDDDDDDDDDDDDDD
</td>
</tr>
</table>

Only one checkbox between two <td> at each <tr>

I have a code like this:
<tr>
<td>
<input type="checkbox" name="ordered[]" value="xxx"></input>
</td>
<td>
<input type="checkbox" name="inStock[]" value="yyy"></input>
</td>
</tr>
The code is repeated for each result in MySQL.
Also I'm using this code:
<script>
$('input[type="checkbox"]').on('change', function() {
// uncheck sibling checkboxes (checkboxes on the same row)
$(this).siblings().prop('checked', false);
});
</script>
I need to select only one checkbox per row (per table tr). What should I change in javascript?
Thanks!
I think you need something like this
$( document ).ready(function() {
$('input[type="checkbox"]').on('change', function() {
var checkedValue = $(this).prop('checked');
// uncheck sibling checkboxes (checkboxes on the same row)
$(this).closest('tr').find('input[type="checkbox"]').each(function(){
$(this).prop('checked',false);
});
$(this).prop("checked",checkedValue);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="checkboxes">
<tr>
<td>
<input type="checkbox" name="inStock[]" />inStock
</td>
<td>
<input type="checkbox" name="ordered[]" value="xxx" />ordered
</td>
</tr>
<tr>
<td>
<input type="checkbox" name="inStock[]" value="yyy" />inStock
</td>
<td>
<input type="checkbox" name="ordered[]" value="xxx" />ordered
</td>
</tr>
</table>
I think what you are asking for is a RadioButton. Just give them different ids but the same name and you will be able to select just one of them.
Try applying selector based on element name:
$('input[name="ordered[]"]').on('change', function() {
Or you would probably want to add some other attribute to identify the specific element you wish to select.
Since you haven't specified which sibling, say you can grab the first element out of a jQuery object using first:
$(this).siblings().first().prop('checked', false);
You can also do
$(this).siblings(".bar").eq(0).text()
You can use the eq method to reduce the matched set of elements to one at a specific index:
If you use radio buttons and use the same name for all of them, you are only able to select one radio button at a time and the other ones gets uncheked and like our friend mentioned you need to include your <td></td> tags in <tr></tr>tags.

Getting nearest text box to radio button in table

I am having trouble getting the text box nearest to my selected radio button. Here is what I have tried so far which keeps returning me 'undefined'.
HTML:
<fieldset class="capacity-field">
<legend>Capacity</legend>
<table style="margin-bottom: 20px">
<tr>
<td>
<input type="radio" name="capacity" value="raw" checked>Raw (TB):
</td>
<td>
<input type="text" name="raw-capacity" value="256" size="2"> TB
</td>
</tr>
<tr>
<td>
<input type="radio" name="capacity" value="usable">Usable (TB):
</td>
<td>
<input type="text" name="usable-capacity" value="161.28" size="2"> TB
</td>
</tr>
<tr>
<td>
<input type="radio" name="capacity" value="effective">Effective (TB):
</td>
<td>
<input type="text" name="effective-capacity" value="161.28" size="2"> TB
</td>
</tr>
</table>
JavaScript/jQuery
function cap_growth_update(toUpdate) {
var capacity = $("input[name='capacity']:checked").next("input[type='text']").val();
alert(capacity);
}
$(document).ready(function(){
cap_growth_update("T");
});
I know the value of toUpdate is arbitrary at this point, but it will be used as a selector later down the line and thus is included.
The jQuery next() function looks for a sibling element, but since these elements are separated under different td elements, you'll have to climb up the DOM:
$("input[name='capacity']:checked").closest("tr").find("input[type='text']").val();
So what it does, is to go to the closest parent, and then search for the children text input.
Try using parents() with eq() and find()
$("input[name='capacity']:checked").parents().eq(1).find("input[type='text']").val();
Note this is only a suggestion I make based on your markup, your goal could be achieved in other ways (jQuery is a rich library to traverse and manipulate DOM)
$(function() {
$("input:radio").click(function() {
if ($(this).is(":checked")) {
var value = $(this).closest("tr").find("input:text").val();
}
});
});
The code checks for a click event on a radio element then check if the element is checked, if it's checked then obtain the parent row of the radio element, find an input text inside the row an get the value of the input text the it saves the value at the var value, so you can do whatever with the value :)
Regards!

Hiding other rows in a table when checkbox is selected

<table id="linkedin_match">
<tr>
<th>Name</th>
<th>Location</th>
<th>Industry</th>
<th>Company</th>
<th>Position</th>
<th> </th>
<th> </th>
</tr>
<tr>
<td>Moses Gonzales</td>
<td>Greater Seattle Area</td>
<td>Chemicals</td>
<td>Superior Grocers</td>
<td>WC Claim Manager</td>
<td>Invite</td>
<td><input type="checkbox" id="match"/></td>
</tr>
<tr>
<td>Moses Gonzales</td>
<td>Greater Seattle Area</td>
<td>Chemicals</td>
<td>Superior Grocers</td>
<td>WC Claim Manager</td>
<td>Invite</td>
<td><input type="checkbox" id="match"/></td>
</tr>
</table>
With the table above, how would I perform the logic, such that if the checkbox is selected, the other rows will hide? The rows are not limited to just two. It could be five, it could be ten, it can be just one. Currently my code is :
$('document').ready(function() {
var tr = $('#linkedin_match tr');
});
Now I don't know what to do with the tr. I'm kinda new to JS too. Thanks.
You can do this way. ids must be unique so change match as class name.
$(document).ready(function() {
$('#linkedin_match .match').change(function(){ //bind change event to the checkboxes
var $this = $(this);
$('#linkedin_match').find('tr:gt(0)').not($this.closest('tr')).toggle();
//since all trs are visible you can use toggle to toggle all the trs but not the one that is a parent of this.
//And un checking will bring all of them back to visible state.
});
});
Fiddle
if you have no control over changing the id to class or add a class, then you can target the checkbox
$('#linkedin_match :checkbox').change(function(){...});
gt(0) - To select the rows with index greater than 0. i.e to avoid the first one.
closest('tr') - To get the parent tr of the checked element.
not($this.closest('tr')) - To add a filter. i.e to exclude the current row.
toggle() - To toggle the element's state.
Add a checkbox
<input type="checkbox" class="check"> Check me
then invoke jquery toggle
$('.check').click(function(){
$('td.hide').toggle();
});
Fiddle: http://jsfiddle.net/webbymatt/DLxjR/
P.s. in my example I have put a class on the cell I want to hide, this could also be applied to entire rows. In this case:
<td class="hide">WC Claim Manager</td>
First off you shouldn't have two elements with the same id. change those to classes and you could do the following:
$(document).on('click', '.match', function(){
if ($(this).is(':checked')) {
$('.match').closest('tr').hide();
$(this).closest('tr').show();
} else { $('.match').closest('tr').show(); }
});
This solution will show all rows with a checkbox when a box is unchecked, and only show the relevant row when the checkbox is checked.

JQuery add class with name of closest label

I have a table that needs some custom theming. It has a lot of text inputs and they all need custom widths. I figured it would be nice to simply add custom CSS classes based on the label name of each field. I am part of the way there but for some reason I am picking up all the label names for any given label in the table, not simply the closest one as I desire.
Here is my JQuery:
$('td.label-text', this).each(function() {
// add class with name of the label text
$('td.input-text').addClass($(this).text().replace(/[^a-z]/gi,'').toLowerCase() + ' ').closest("td.label-text");
});
Here is some sample HTML output:
<tr>
<td class="label-text">Rule Name*:</td>
<td class="input-text effectivedate rulename employeeid createrulefor ipaddress active searchby">
<input type="text" name="ruleName" value="">
</td>
</tr>
<tr>
<td class="label-text">Employee ID:</td>
<td class="input-text effectivedate rulename employeeid createrulefor ipaddress active searchby">
<input type="text" name="employeeId" value="" id="empnotext">
</td>
</tr>
As you can see all label names get added to every td .input-text class, not the nearest (closest) one. I am sure I am doing something wrong but not sure what.
I am also wondering if a class can be added based on the input name
You have to use this inside the loop. Currently, you're selecting all elements with selector td.input-text (at each iteration). Fiddle: http://jsfiddle.net/WCTyz/2/
$('td.input-text input', this).each(function() {
// add class with name of the label text
var $this = $(this);
var addclass = $this.parents("tr:first").children("td:first")
.text().replace(/[^a-z]/gi,'').toLowerCase();
$this.addclass(addClass);
});
Also, the addClass method automatically deals with separating spaces. You don't have to manually postfix your class name by a space.
Explanation of selector:
td.input-text input For each <td class="input-text"> ???? <input> ??? </td> :
Get class name:
.parents("tr:first") Select the current row
.children("td:first") Select the first cell
.text() Get the textual value

Categories

Resources