I have dynamic table https://jsfiddle.net/vc5dbtw9/8/ that is generated through my database.
This is just a small example, actual table is much bigger and it will grow in size in time(that's why it needs to me dynamical).
Some fields need to be mandatory to fill in, so I made a column in database and as you can see hidden label (IDKarakteristike) is generated with the values True and False.
I need some kind of a jQuery to dynamically check if the label in the row is true or false and make textbox in the same row mandatory to fill in or not(depending on the label) on button click.
Can someone please help me with jQuery?
I need something like this, warning when the button is clicked.
$('#myButton').on('click', function () {
$("input").prop('required',true);
});
Thanks in advance !
Here is the working example. Find the spans, get only the spans with boolean value, for each span find the parent row and then find the form element within this row:
$(function () {
$("#myButton").on("click", function () {
// Loop all span elements with target class
$(".IDKarakteristike").each(function (i, el) {
// Skip spans which text is actually a number
if (!isNaN($(el).text())) {
return;
}
// Get the value
var val = $(el).text().toUpperCase();
var isRequired = (val === "TRUE") ? true :
(val === "FALSE") ? false : undefined;
// Mark the textbox with required attribute
if (isRequired) {
// Find the form element
var target = $(el).parents("tr").find("input,select");
// Mark it with required attribute
target.prop("required", true);
// Just some styling
target.css("border", "1px solid red");
}
});
})
});
.IDKarakteristike {
display:none !important;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<table cellspacing="0" cellpadding="4" id="MainContent_gvKarakteristike" style="color:#333333;border-collapse:collapse;">
<tr style="color:White;background-color:#507CD1;font-weight:bold;">
<th scope="col">Characteristic</th><th scope="col"> </th><th scope="col">Description</th>
</tr><tr style="background-color:#EFF3FB;">
<td>
<span id="MainContent_gvKarakteristike_Karakteristike_0" margin-Left="100px" style="display:inline-block;font-family:Georgia;height:30px;width:150px;">PFD Total value</span>
</td><td>
<span id="MainContent_gvKarakteristike_Label_0" class="IDKarakteristike" margin-Left="100px" style="display:inline-block;font-family:Georgia;height:30px;width:150px;">1</span>
<span id="MainContent_gvKarakteristike_Label1_0" class="IDKarakteristike" margin-Left="100px" style="display:inline-block;font-family:Georgia;height:30px;width:150px;">True</span>
</td><td>
<input name="ctl00$MainContent$gvKarakteristike$ctl02$txtBoxOpis" type="text" maxlength="4" id="MainContent_gvKarakteristike_txtBoxOpis_0" margin-Left="100px" style="font-family:Georgia;height:30px;width:150px;" />
</td>
</tr><tr style="background-color:White;">
<td>
<span id="MainContent_gvKarakteristike_Karakteristike_1" margin-Left="100px" style="display:inline-block;font-family:Georgia;height:30px;width:150px;">PFD Wear </span>
</td><td>
<span id="MainContent_gvKarakteristike_Label_1" class="IDKarakteristike" margin-Left="100px" style="display:inline-block;font-family:Georgia;height:30px;width:150px;">2</span>
<span id="MainContent_gvKarakteristike_Label1_1" class="IDKarakteristike" margin-Left="100px" style="display:inline-block;font-family:Georgia;height:30px;width:150px;">False</span>
</td><td>
<input name="ctl00$MainContent$gvKarakteristike$ctl03$txtBoxOpis" type="text" maxlength="6" id="MainContent_gvKarakteristike_txtBoxOpis_1" margin-Left="100px" style="font-family:Georgia;height:30px;width:150px;" />
</td>
</tr><tr style="background-color:#EFF3FB;">
<td>
<span id="MainContent_gvKarakteristike_Karakteristike_2" margin-Left="100px" style="display:inline-block;font-family:Georgia;height:30px;width:150px;">PFD Weight g/m²</span>
</td><td>
<span id="MainContent_gvKarakteristike_Label_2" class="IDKarakteristike" margin-Left="100px" style="display:inline-block;font-family:Georgia;height:30px;width:150px;">3</span>
<span id="MainContent_gvKarakteristike_Label1_2" class="IDKarakteristike" margin-Left="100px" style="display:inline-block;font-family:Georgia;height:30px;width:150px;">False</span>
</td><td>
<input name="ctl00$MainContent$gvKarakteristike$ctl04$txtBoxOpis" type="text" maxlength="8" id="MainContent_gvKarakteristike_txtBoxOpis_2" margin-Left="100px" style="font-family:Georgia;height:30px;width:150px;" />
</td>
</tr><tr style="background-color:White;">
<td>
<span id="MainContent_gvKarakteristike_Karakteristike_3" margin-Left="100px" style="display:inline-block;font-family:Georgia;height:30px;width:150px;">PFD Surface
</span>
</td><td>
<span id="MainContent_gvKarakteristike_Label_3" class="IDKarakteristike" margin-Left="100px" style="display:inline-block;font-family:Georgia;height:30px;width:150px;">5</span>
<span id="MainContent_gvKarakteristike_Label1_3" class="IDKarakteristike" margin-Left="100px" style="display:inline-block;font-family:Georgia;height:30px;width:150px;">True</span>
</td><td>
<select name="ctl00$MainContent$gvKarakteristike$ctl05$ddlOpis" id="MainContent_gvKarakteristike_ddlOpis_3" margin-Left="100px" style="font-family:Georgia;height:35px;width:161px;">
<option selected="selected" value=""></option>
<option value="1">Proteco
</option>
<option value="2">Proteco Oil
</option>
<option value="3">Classic
</option>
<option value="4">Natura
</option>
<option value="5">No Surface t</option>
</select>
</td>
</tr><tr style="background-color:#EFF3FB;">
<td>
<span id="MainContent_gvKarakteristike_Karakteristike_4" margin-Left="100px" style="display:inline-block;font-family:Georgia;height:30px;width:150px;">PFD product
</span>
</td><td>
<span id="MainContent_gvKarakteristike_Label_4" class="IDKarakteristike" margin-Left="100px" style="display:inline-block;font-family:Georgia;height:30px;width:150px;">9</span>
<span id="MainContent_gvKarakteristike_Label1_4" class="IDKarakteristike" margin-Left="100px" style="display:inline-block;font-family:Georgia;height:30px;width:150px;">True</span>
</td><td>
<input name="ctl00$MainContent$gvKarakteristike$ctl06$txtBoxOpis" type="text" maxlength="60" id="MainContent_gvKarakteristike_txtBoxOpis_4" margin-Left="100px" style="font-family:Georgia;height:30px;width:150px;" />
</td>
</tr>
</table>
</div>
<input type="button" class="button" id="myButton" value="Save"/>
This is how to go to the previous TD and find the second span (or you can use class seletor for IDKarakteristike) and check its value to decide:
$(document).ready(function(){
$("input").each(function(){
if ($($this).closest('td').prev('td').find("span").eq(1).html()=='true'){
$(this).prop('required',true);
}
})
})
I have updated the fiddle : https://jsfiddle.net/vc5dbtw9/56/
Surround your html code with form tag and convert the button to submit and put the following script and you are good to go!
$('#myButton').on('click', function () {
$('#MainContent_gvKarakteristike tr').each(function(e){
var mandatory = $(this).find('.IDKarakteristike:last').text().toLowerCase();
if(mandatory == 'true')
{
$(this).find('input,select').prop('required','required');
}
else
{
$(this).find('input,select').prop('required',false);
}
});
});
Related
I have an HTML table. On the table I have an input textbox. Next to it. (appended in the HTML) I have an anchor. All I want the anchor to do (at the moment), is get and set the value in the textbox.
Here is my (abbreviated code) HTML Code:
<tr>
<td class="t-Report-cell" headers="DEPARTMENT">
<input type="text" name="f02" size="20" maxlength="2000" value="" col_name="DEPARTMENT" class="u-TF-item u-TF-item--text" autocomplete="off" />
<td class="t-Report-cell" headers="DESCRIPTION">
<input type="text" name="f03" size="20" maxlength="2000" value="soup" col_name="DESCRIPTION" class="u-TF-item u-TF-item--text" autocomplete="off">
<a href="javascript:get_desc( $(this).closest('tr') );" class="a-Button a-Button--popupLOV">
<span class="a-Icon icon-popup-lov">
<span class="visuallyhidden">List</span>
</span>
</a>
<input type="hidden" id="fcs_0001" name="fcs" value="FB0D0992B787C5475D897B224F1FAE9D7547BC497FADE2E32B252FFAE2F31CE235225E0D645509C8E3576895FB814229B832CBF0BC11DA3F784FDE9BD5ADED86" autocomplete="off">
<input type="hidden" id="fcud_0001" name="fcud" value="U" autocomplete="off" />
</tr>
Notice I have an input type=text name=f03 with a value of "soup" (I've also given it another attribute to try and target it. (col_name="DESCRIPTION")
Then under it, I have an anchor which calls a JavaScript function and passes in the current row.
My simple function does the following:
function get_desc(thisRow) {
console.log(thisRow);
var desc = thisRow.find("input[name='f03']");
console.log(desc);
console.log(desc.val());
console.log(desc.text());
}
So it passes in the current row, looks for the input, then tries to get the value.
I can see on console.log that the correct selector is found, but nothing I do gets the value.
As I say, I have lots of JavaScript code in my app, so I've been staring at this wondering what I'm doing wrong
Some debugging shows that this is the window object when you use <a href="javascript:get_desc(this);", :
function get_desc(link) {
console.log(link === window);
}
click me
If you must use html attributes, then you can use onclick='get_desc(this):
function get_desc(link) {
thisRow = $(link).closest('tr')
var desc = thisRow.find("input[name='f03']");
console.log(desc.val());
}
<table>
<tr>
<td>
<input type="text" name="f03" value="soup">
click me
</td>
</tr>
</table>
Alternatively, embrace jquery events (or vanilla events)
$(".link").click(function() {
thisRow = $(this).closest('tr')
var desc = thisRow.find("input[name='f03']");
console.log(desc.val());
});
<table>
<tr>
<td>
<input type="text" name="f03" value="soup">
<a href="javascript:return false;" class='link'>click me</a>
</td>
</tr>
</table>
I used querySelector instead of find and value property of input.
function get_desc(thisRow) {
console.log(thisRow);
var desc = thisRow.querySelector("input[name='f03']");
console.log(desc.value);
}
<table>
<tr onclick="get_desc(this);">
<td class="t-Report-cell" headers="DEPARTMENT">
<input type="text" name="f02" size="20" maxlength="2000" value="" col_name="DEPARTMENT" class="u-TF-item u-TF-item--text" autocomplete="off" />
<td class="t-Report-cell" headers="DESCRIPTION">
<input type="text" name="f03" size="20" maxlength="2000" value="soup" col_name="DESCRIPTION" class="u-TF-item u-TF-item--text" autocomplete="off">
<a href="#" class="a-Button a-Button--popupLOV">
<span class="a-Icon icon-popup-lov">
<span class="visuallyhidden">List</span>
</span>
</a>
<input type="hidden" id="fcs_0001" name="fcs" value="FB0D0992B787C5475D897B224F1FAE9D7547BC497FADE2E32B252FFAE2F31CE235225E0D645509C8E3576895FB814229B832CBF0BC11DA3F784FDE9BD5ADED86" autocomplete="off">
<input type="hidden" id="fcud_0001" name="fcud" value="U" autocomplete="off" />
</tr>
</table>
instead of href use onClick attribute of anchor.
Try this;
<a href="#" onClick="javascript:get_desc( $(this).closest('tr') );" class="a-Button a-Button--popupLOV">
A new row is dynamically creating on clicking "add Row" button through function in jQuery.
But when I select radio input in new row then selected value of previous radio input is removing.
Please run and see the codes as below:
enter image description here
function add_row(table_row_count)
{
$("#add-row_"+table_row_count).hide();
$("#delete-row_"+table_row_count).hide();
var table_row_count = parseInt(table_row_count);
table_row_count += 1;
var markup =
'<tr id="tbl_row_'+table_row_count+'" >'+
'<td><label>'+table_row_count+'</label></td>'+
'<td>'+
'<label>Value in Range? :</label>'+
'<input type="radio" name="option" id="option_1_row_'+table_row_count+'" value="1" > YES'+
'<input type="radio" name="option" id="option_2_row_'+table_row_count+'" value="2" > NO'+
'</td>'+
'<td id="capacity_from_row_'+table_row_count+'" >'+
'<label>Range From :</label><br>'+
'<input type="text" name="capacity_from[]" id="capacity_from_'+table_row_count+'" />'+
'</td>'+
'<td>'+
'<label id="lbl_capacity_range_'+table_row_count+'" >Range Upto :</label><br>'+
'<input type="text" name="capacity_upto[]" id="capacity_upto_'+table_row_count+'" />'+
'</td>'+
'<td class="align-middle"></i> Add Row</td>'+
'<td class="align-middle"></i> Delete Row</td>'+
'</tr>';
var table = $("#tbl_details tbody");
table.append(markup);
}
function delete_row(table_row_count)
{
var r = confirm("Are you sure to delete row");
if(r == false){
return;
}
var table_row_count = parseInt(table_row_count);
var previous_row = table_row_count - 1;
$("#add-row_"+previous_row).show();
if(previous_row != 1){
$("#delete-row_"+previous_row).show();
}
$("#tbl_row_"+table_row_count).remove();
}
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script type="text/javascript" src="add.js"></script>
</head>
<body>
<h3>Enter Details</h3>
<table class="table table-striped" id="tbl_details">
<tbody>
<tr id="row_1">
<td>1.</td>
<td>
<label>Value in Range? :</label>
<input type="radio" name="option" id="option_1_row_1" value="1" checked="checked" > YES
<input type="radio" name="option" id="option_2_row_1" value="2" > NO
</td>
<td id="capacity_from_row_1" >
<label>Range From :</label><br>
<input type="text" name="capacity_from[]" id="capacity_from_1" />
</td>
<td>
<label id="lbl_capacity_range_1" >Range Upto :</label><br>
<input type="text" name="capacity_upto[]" id="capacity_upto_1" />
</td>
<td class="align-middle"></i> Add Row</td>
<td class="align-middle"></td>
</tr>
</tbody>
</table>
</body>
</html>
How to solve the issue. kindly help me.
Thanks in advance.
Different radio button groups are created when the name attribute of the radio buttons is different. Also, in the solution below, I made it easier to express dynamic content by using template literals.
Note the following statement in the dynamic element written into the markup variable in the add_row() method:
<input type="radio" name="option${counter}" id="option_1_row_${table_row_count}" value="1"> YES
<input type="radio" name="option${counter}" id="option_2_row_${table_row_count}" value="2"> NO
/* This variable will be used to create new radio button groups. */
let counter = 0;
function add_row(table_row_count) {
$("#add-row_"+table_row_count).hide();
$("#delete-row_"+table_row_count).hide();
var table_row_count = parseInt(table_row_count);
table_row_count += 1;
/* With each iteration, the content of the counter variable is incremented. */
++counter;
var markup =
`<tr id="tbl_row_${table_row_count}">
<td>
<label>${table_row_count}</label>
</td>
<td>
<label>Value in Range? :</label>
<!-- Note the name="option${counter}" statement so that the radio buttons have different groups. -->
<input type="radio" name="option${counter}" id="option_1_row_${table_row_count}" value="1"> YES
<input type="radio" name="option${counter}" id="option_2_row_${table_row_count}" value="2"> NO
</td>
<td id="capacity_from_row_${table_row_count}">
<label>Range From :</label><br>
<input type="text" name="capacity_from[]" id="capacity_from_${table_row_count}"/>
</td>
<td>
<label id="lbl_capacity_range_${table_row_count}">Range Upto :</label><br>
<input type="text" name="capacity_upto[]" id="capacity_upto_${table_row_count}"/>
</td>
<td class="align-middle">
<a href="javascript:void(0)" class="text-success add-row" id="add-row_${table_row_count}" onClick="add_row('${table_row_count}');" >
<i class="fa fa-plus fa-lg text-success" aria-hidden="true"></i> Add Row
</a>
</td>
<td class="align-middle">
<a href="javascript:void(0)" class="text-danger delete-row" id="delete-row_${table_row_count}" onClick="delete_row('${table_row_count}');" >
<i class="fa fa-trash fa-lg text-danger" aria-hidden="true"></i> Delete Row
</a>
</td>
</tr>`
var table = $("#tbl_details tbody");
table.append(markup);
}
function delete_row(table_row_count) {
var r = confirm("Are you sure to delete row");
if(r == false){
return;
}
var table_row_count = parseInt(table_row_count);
var previous_row = table_row_count - 1;
$("#add-row_"+previous_row).show();
if(previous_row != 1){
$("#delete-row_"+previous_row).show();
}
$("#tbl_row_"+table_row_count).remove();
}
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script type="text/javascript" src="add.js"></script>
</head>
<body>
<h3>Enter Details</h3>
<table class="table table-striped" id="tbl_details">
<tbody>
<tr id="row_1">
<td>1.</td>
<td>
<label>Value in Range? :</label>
<input type="radio" name="option" id="option_1_row_1" value="1" checked="checked" > YES
<input type="radio" name="option" id="option_2_row_1" value="2" > NO
</td>
<td id="capacity_from_row_1" >
<label>Range From :</label><br>
<input type="text" name="capacity_from[]" id="capacity_from_1" />
</td>
<td>
<label id="lbl_capacity_range_1" >Range Upto :</label><br>
<input type="text" name="capacity_upto[]" id="capacity_upto_1" />
</td>
<td class="align-middle"></i> Add Row</td>
<td class="align-middle"></td>
</tr>
</tbody>
</table>
</body>
</html>
This is happening because you are using the same name for radio button. And it is default behavior of radio that if you are using the same name for radio button then only one can be selected at time.
For Example
1.) If you have two radios with same name
Only one value can be selected at a time.
2.) Now after adding another row your code will look like
<input name="option" type="radio" value="true"/>
<input name="option" type="radio" value="false"/
<input name="option" type="radio" value="true"/>
<input name="option" type="radio" value="false"/>
name is same for all radio buttons so only one will be selected at a time.
Fix:
In order to fix this issue while adding new row append row number in front of name. That will fix the issue like you did for id attribute.
'<td>'+
'<label>Value in Range? :</label>'+
'<input type="radio" name="option_'+table_row_count+'" id="option_1_row_'+table_row_count+'" value="1" > YES'+
'<input type="radio" name="option_'+table_row_count+'" id="option_2_row_'+table_row_count+'" value="2" > NO'+
'</td>'+
Fixing this will fix the issue.
*** Change dynamic radio input name. here, your code create all dynamic radio input with the same name. ***
I have results shows up inside a table, I designed it to show as grid by separating them by td for each.
I used a JS code to filter the results by a text written in textbox, but the only results shows is the labels!
I want each td shows as a result, complete with the contents (Image + Input + label).
Here's the JS code & example of a table same what I have:
$(document).ready(function() {
$("#filter").on("keyup", function() {
var value = $(this).val().toLowerCase();
$("#table *").filter(function() {
$(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
});
});
});
<table>
<input type="text" id="filter">
<div name="table">
<td>
<label>Product1</label>
<img src='/img/a.jpg'>
<input type="text" value="55">
</td>
<td>
<label>Product2</label>
<img src='/img/b.jpg'>
<input type="text" value="70">
</td>
<td>
<label>Product3</label>
<img src='/img/c.jpg'>
<input type="text" value="20">
</td>
</div>
</table>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Use closest this link to get parent td from your search and then toggle visibility.
below is logic to your solution.
$(this).closest("td").toggle($(this).text().toLowerCase().indexOf(value) > -1)
$(document).ready(function() {
$("#filter").on("keyup", function() {
var value = $(this).val().toLowerCase();
$("table label").filter(function() {
$(this).closest("td").toggle($(this).text().toLowerCase().indexOf(value) > -1)
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<input type="text" id="filter">
<div name="table">
<td>
<label>Product1</label>
<img src='/img/a.jpg'>
<input type="text" value="55">
</td>
<td>
<label>Product2</label>
<img src='/img/b.jpg'>
<input type="text" value="70">
</td>
<td>
<label>Product3</label>
<img src='/img/c.jpg'>
<input type="text" value="20">
</td>
</div>
</table>
I am trying to select a list of checkboxes. The inputs are generated dynamically and there is more than one list of checkboxes - so I created a global function by sending in the id of the < table > so that the correct list of checkboxes are checked/unchecked.
I think the looping of the nodes in the nodelist is causing the problem but in my mind, it makes sense, but the checkboxes are not checking and there is no error popping up either.
function checkAll(name) {
var nodeList = $(name).next('input[type="checkbox"]');
var nodes = $(nodeList);
nodes.each(function(node) {
if (!node.disabled) {
node.checked = true;
}
});
}
<table summary="User locations" id="LocationsTable">
<tr>
<th>
<input type='hidden' name='StoreSelector' id='StoreSelector' value='true'>
Other locations (multi-store)
<button type="button" onclick="javascript:checkAll('LocationsTable');">All</button>
<button type="button" onclick="javascript:uncheckAll('LocationsTable');">None</button>
</th>
</tr>
<tr id="LocationRow">
<td>
<input type="checkbox" name="Store" id="Store" value="Store"> <span id="StoreName">Store 1</span>
</td>
</tr>
</table>
You can use find here very well.
Consider that your name is an ID, so put in fron of your name the hashtag #name.
Also I would recommend using an event listener. I updated your code to use it therefore I gave your btn an id.
document.getElementById('btn').addEventListener('click', function(){checkAll('LocationsTable')})
function checkAll(name) {
var nodeList = [...$(`#${name}`).find('input[type="checkbox"]')];
nodeList.forEach(function(node) {
if (!node.disabled) {
node.checked = true;
}
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table summary="User locations" id="LocationsTable">
<tr>
<th>
<input type='hidden' name='StoreSelector' id='StoreSelector' value='true'>
Other locations (multi-store)
<button id='btn' type="button" >All</button>
<button type="button" onclick="javascript:uncheckAll('LocationsTable');">None</button>
</th>
</tr>
<tr id="LocationRow">
<td>
<input type="checkbox" name="Store" id="Store" value="Store"> <span id="StoreName">Store 1</span>
<input type="checkbox" name="Store" id="Store" value="Store"> <span id="StoreName">Store 1</span>
<input type="checkbox" name="Store" id="Store" value="Store"> <span id="StoreName">Store 1</span>
</td>
</tr>
</table>
simply use querySelectorAll() :
function checkAll(name)
{
document.querySelectorAll(`#${name} input[type=checkbox]`).forEach(nod=>
{
if (!nod.disabled) nod.checked = true;
});
}
You want to prepend the selector passed to the functions with a # - an id selector. Then all you need in the function is:
$(name).find('input[type="checkbox"]').not(':disabled').prop('checked',true);
DEMO
function checkAll(name) {
$(name).find('input[type="checkbox"]').not(':disabled').prop('checked',true);
}
function uncheckAll(name) {
$(name).find('input[type="checkbox"]').not(':disabled').prop('checked',false);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table summary="User locations" id="LocationsTable">
<tr>
<th>
<input type='hidden' name='StoreSelector' id='StoreSelector' value='true'>
Other locations (multi-store)
<button type="button" onclick="javascript:checkAll('#LocationsTable');">All</button>
<button type="button" onclick="javascript:uncheckAll('#LocationsTable');">None</button>
</th>
</tr>
<tr id="LocationRow">
<td>
<input type="checkbox" name="Store" id="Store1" value="Store"> <span id="StoreName">Store 1</span>
<input type="checkbox" name="Store" id="Store2" value="Store"> <span id="StoreName">Store 2</span>
<input type="checkbox" name="Store" id="Store3" value="Store"> <span id="StoreName">Store 3</span>
<input type="checkbox" name="Store" id="Store4" value="Store" disabled> <span id="StoreName">Store 4</span>
</td>
</tr>
</table>
OPTION 2
However, I would not advise use of inline JS. Separate your JS, CSS, and HTML as in the following demo:
$('button.all').on('click', function() {
//this refers to button.all
$(this)
//go up the tree to select the table
.closest('table')
//go down to the checkboxes and check them
.find('input[type="checkbox"]').not(':disabled').prop('checked',true);
});
DEMO
$('button.all').on('click', function() {
//this refers to button.all
$(this)
//go up the tree to select the table
.closest('table')
//go down to the checkboxes and check them
.find('input[type="checkbox"]').not(':disabled').prop('checked',true);
});
$('button.none').on('click', function() {
//this refers to button.none
$(this)
//select tabl
.closest('table')
//select checkbox and uncheck
.find('input[type="checkbox"]').not(':disabled').prop('checked',false);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table summary="User locations" id="LocationsTable">
<tr>
<th>
<input type='hidden' name='StoreSelector' id='StoreSelector' value='true'>
Other locations (multi-store)
<button type="button" class="all">All</button>
<button type="button" class="none">None</button>
</th>
</tr>
<tr id="LocationRow">
<td>
<input type="checkbox" name="Store" id="Store1" value="Store"> <span id="StoreName">Store 1</span>
<input type="checkbox" name="Store" id="Store2" value="Store"> <span id="StoreName">Store 2</span>
<input type="checkbox" name="Store" id="Store3" value="Store"> <span id="StoreName">Store 3</span>
<input type="checkbox" name="Store" id="Store4" value="Store" disabled> <span id="StoreName">Store 4</span>
</td>
</tr>
</table>
OPTION 3
Alternatively, you can use one button to toggle all the checkboxes.
$('button.toggle').on('click', function() {
//this refers to button.all
$(this)
//go up the tree to select the table
.closest('table')
//go down to the checkboxes and check them
.find('input[type="checkbox"]').not(':disabled').prop('checked',function() {return !this.checked});
});
DEMO
$('button.toggle').on('click', function() {
//this refers to button.all
$(this)
//go up the tree to select the table
.closest('table')
//go down to the checkboxes and check them
.find('input[type="checkbox"]').not(':disabled').prop('checked',function() {return !this.checked});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table summary="User locations" id="LocationsTable">
<tr>
<th>
<input type='hidden' name='StoreSelector' id='StoreSelector' value='true'>
Other locations (multi-store)
<button type="button" class="toggle">All</button>
<!--button type="button" class="none">None</button-->
</th>
</tr>
<tr id="LocationRow">
<td>
<input type="checkbox" name="Store" id="Store1" value="Store"> <span id="StoreName">Store 1</span>
<input type="checkbox" name="Store" id="Store2" value="Store"> <span id="StoreName">Store 2</span>
<input type="checkbox" name="Store" id="Store3" value="Store"> <span id="StoreName">Store 3</span>
<input type="checkbox" name="Store" id="Store4" value="Store" disabled> <span id="StoreName">Store 4</span>
</td>
</tr>
</table>
NOTE
Please note that in each option no reference is made to the id of the particular table in question as the event handler keeps the actions within the particular table whose button was clicked.
So I have these checkboxes with crazy IDs because reasons that I can't change. For example:
<td>
<span title=BBB class="ms-RadioText">
<input id = Checkbox1 type=checkbox/>
<label for="Checkbox1">BBB</label>
</span>
<span title=AAA class="ms-RadioText">
<input id = Checkbox2 type=checkbox/>
<label for="Checkbox2">AAA</label>
</span>
</td>
And, of course, they appear non-alphabetically. How do I sort this alphabetically using native JavaScript, JQuery, or CSS, as I am not allowed to alter the order of the checkboxes in HTML?
jQuery sort and read the title attribute
$('td').each(function() {
var td = $(this)
td.find('span').sort(function(a, b) {
return a.title.localeCompare(b.title)
}).appendTo(td)
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<td>
<span title=BBB class="ms-RadioText">
<input id="Checkbox1" type="checkbox"/>
<label for="Checkbox1">BBB</label>
</span>
<span title=AAA class="ms-RadioText">
<input id="Checkbox2" type="checkbox"/>
<label for="Checkbox2">AAA</label>
</span>
</td>
</tr>
<tr>
<td>
<span title=FFF class="ms-RadioText">
<input id="Checkbox1b" type="checkbox"/>
<label for="Checkbox1b">FFF</label>
</span>
<span title=ZZZ class="ms-RadioText">
<input id="Checkbox2b" type="checkbox"/>
<label for="Checkbox2b">ZZZ</label>
</span>
<span title=EEE class="ms-RadioText">
<input id="Checkbox3b" type="checkbox"/>
<label for="Checkbox3b">EEE</label>
</span>
</td>
</tr>
</table>
Without jQuery
document.querySelectorAll('td').forEach(function(td) {
const spans = td.querySelectorAll('span')
const ordered = Array.from(spans).sort( function (a,b) {
return a.title.localeCompare(b.title)
})
var frag = ordered.reduce(function (frag, span){
frag.appendChild(span)
return frag
}, document.createDocumentFragment())
td.appendChild(frag)
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<td>
<span title=BBB class="ms-RadioText">
<input id="Checkbox1" type="checkbox"/>
<label for="Checkbox1">BBB</label>
</span>
<span title=AAA class="ms-RadioText">
<input id="Checkbox2" type="checkbox"/>
<label for="Checkbox2">AAA</label>
</span>
</td>
</tr>
<tr>
<td>
<span title=FFF class="ms-RadioText">
<input id="Checkbox1b" type="checkbox"/>
<label for="Checkbox1b">FFF</label>
</span>
<span title=ZZZ class="ms-RadioText">
<input id="Checkbox2b" type="checkbox"/>
<label for="Checkbox2b">ZZZ</label>
</span>
<span title=EEE class="ms-RadioText">
<input id="Checkbox3b" type="checkbox"/>
<label for="Checkbox3b">EEE</label>
</span>
</td>
</tr>
</table>
With vanilla JavaScript you can sort your checkboxes with the following function.
function sortCheckboxesByLabel(parentElement) {
var children = Array.prototype.slice.call(parentElement.children), // Convert to true array.
fragment = document.createDocumentFragment();
// Sort alphabetically.
children.sort((item1, item2) => item1.querySelector('label').innerText > item2.querySelector('label').innerText ? 1 : -1);
// Add to fragment.
for(var i = 0; i < children.length; i++) {
fragment.appendChild(children[i]);
}
// Append back to document.
parentElement.appendChild(fragment);
}
It takes their parent element as it’s only parameter. It converts the parent elements children to an array and then sorts the array alphabetically. It then appends those items into a document fragment and finally back to the parent element.
You could take advantage of the DOM API to grab the span elements from the parent, re-order them, and append a document fragment back to the original parent element. Something like below:
const orderEls = () => {
//Get an array of the elements we want to sort
const spanEls = Array.from(document.querySelectorAll('span'));
//Generate a doc fragment containing the ordered els
const frag = spanEls
.sort((a, b) => a.title > b.title ? 1 : -1)
.reduce((accum, spanEl) => {
accum.appendChild(spanEl);
return accum;
}, document.createDocumentFragment());
//Append the ordered els to the parent
document.querySelector('td').appendChild(frag)
};
orderEls();
<table>
<tr>
<td>
<span title="BBB" class="ms-RadioText">
<input id="Checkbox1" type="checkbox" />
<label for="Checkbox1">BBB</label>
</span>
<span title="AAA" class="ms-RadioText">
<input id="Checkbox2" type="checkbox"/>
<label for="Checkbox2">AAA</label>
</span>
</td>
</tr>
</table>