How to get value Check and Uncheck checkbox use JQuery on array - javascript

Now im doing PHP Project combine with JQuery. I want to get value from checkbox both checked and unchecked on array. here is what i try
$(function() {
$('.dealprice').on('input', function(){
if($('.dealprice:checkbox:checked').prop('checked')){
//CHECKED
console.log("Checked");
const getPrice = $(this).closest("tr").find('input[name=itemprice]').val();
console.log(getPrice);
}else{
//UNCHECKED
console.log("Uncheck");
const getPrice = $(this).closest("tr").find('input[name=itemprice]').val();
console.log(getPrice);
}
});
});
i make a sample on this site. https://repl.it/#ferdinandgush/get-value-checkbox please click "RUN" bottom on the top to able test it.
the problem is, when the checkbox checked more then 1 and when i want to uncheck 1 of it. it still return value "True" not "false".
what i want it. each of checkbox can return value wherever i checked and uncheck it.
checked return consolo.log('true');
unchecked return consolo.log('false');
please help

I believe you can just do it like this if ($(this).prop('checked')) {
Then it will only check if the checkbox that you click on is checked or not.
Demo
$(function() {
$('.dealprice').on('input', function() {
if ($(this).prop('checked')) {
//CHECKED
console.log("Checked");
const getPrice = $(this).closest("tr").find('input[name=itemprice]').val();
console.log(getPrice);
} else {
//UNCHECKED
console.log("Uncheck");
const getPrice = $(this).closest("tr").find('input[name=itemprice]').val();
console.log(getPrice);
}
});
});
.tg {border-collapse:collapse;border-spacing:0;}
.tg td{border-color:black;border-style:solid;border-width:1px;font-family:Arial, sans-serif;font-size:14px;
overflow:hidden;padding:10px 5px;word-break:normal;}
.tg th{border-color:black;border-style:solid;border-width:1px;font-family:Arial, sans-serif;font-size:14px;
font-weight:normal;overflow:hidden;padding:10px 5px;word-break:normal;}
.tg .tg-qh0q{background-color:#c0c0c0;color:#000000;font-weight:bold;text-align:center;vertical-align:top}
.tg .tg-0lax{text-align:left;vertical-align:top}
.tg .tg-amwm{font-weight:bold;text-align:center;vertical-align:top}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="tg">
<thead>
<tr>
<th class="tg-qh0q">Item</th>
<th class="tg-qh0q">Price</th>
<th class="tg-qh0q">Deal</th>
</tr>
</thead>
<tbody>
<tr>
<td class="tg-0lax">Book</td>
<td class="tg-0lax">$ 10 <input type="hidden" name="itemprice" value="10"></td>
<td class="tg-0lax"><input type="checkbox" class="dealprice" name="deal[12][0]"></td>
</tr>
<tr>
<td class="tg-0lax">Pencil</td>
<td class="tg-0lax">$ 5 <input type="hidden" name="itemprice" value="5"></td>
<td class="tg-0lax"><input type="checkbox" class="dealprice" name="deal[12][1]"></td>
</tr>
<tr>
<td class="tg-0lax">Pen</td>
<td class="tg-0lax">$ 8 <input type="hidden" name="itemprice" value="8"></td>
<td class="tg-0lax"><input type="checkbox" class="dealprice" name="deal[12][2]"></td>
</tr>
<tr>
<td class="tg-0lax">spidol</td>
<td class="tg-0lax">$ 15 <input type="hidden" name="itemprice" value="15"></td>
<td class="tg-0lax"><input type="checkbox" class="dealprice" name="deal[12][3]"></td>
</tr>
</tbody>
</table>

<script>
$(document).ready(function(){
$(".dealprice").change(function(){
if($(this).is(":checked")){
console.log(true);
} else {
console.log(false);
}
});
});
</script>

Related

Wrong Result Calculate value with checkbox use Jquery

Now im doing some Calculate Checkbox Value Using JQuery and PHP code. The mechanism is, when User checked the checkbox, it will sum the price. I implemented a formula for JQuery but the result it not correct. here is my code
JQUERY
<script>
$(function() {
$('.dealprice').on('input', function(){
const getItemPrice = $(this).closest("tr").find('input[name=itemprice]').val();
var eachPrice = 0;
$('.dealprice:checkbox:checked').each(function(){
eachPrice += isNaN(parseInt(getItemPrice)) ? 0 : parseInt(getItemPrice);
});
$("#totalDeal").text(eachPrice.toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,'));
});
});
</script>
for more detail. i made a sample on this site https://repl.it/#ferdinandgush/Sum-Calculate-checkbox just click "run" button and you can able to test it. i need to display correct calculate following that table format
Please help.
You just have to define getItemPrice inside the loop, otherwise you are calculating it only once for the item that was clicked, instead of doing it for every item.
$(function() {
$('.dealprice').on('input', function(){
var eachPrice = 0;
$('.dealprice:checkbox:checked').each(function(){
const getItemPrice = $(this).closest("tr").find('input[name=itemprice]').val();
eachPrice += isNaN(parseInt(getItemPrice)) ? 0 : parseInt(getItemPrice);
});
$("#totalDeal").text(eachPrice.toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,'));
});
});
<table class="tg">
<thead>
<tr>
<th class="tg-qh0q">Item</th>
<th class="tg-qh0q">Price</th>
<th class="tg-qh0q">Deal</th>
</tr>
</thead>
<tbody>
<tr>
<td class="tg-0lax">Book</td>
<td class="tg-0lax">$ 10 <input type="hidden" name="itemprice" value="10"></td>
<td class="tg-0lax"><input type="checkbox" class="dealprice" name="deal[12][0]"></td>
</tr>
<tr>
<td class="tg-0lax">Pencil</td>
<td class="tg-0lax">$ 5 <input type="hidden" name="itemprice" value="5"></td>
<td class="tg-0lax"><input type="checkbox" class="dealprice" name="deal[12][1]"></td>
</tr>
<tr>
<td class="tg-0lax">Pen</td>
<td class="tg-0lax">$ 8 <input type="hidden" name="itemprice" value="8"></td>
<td class="tg-0lax"><input type="checkbox" class="dealprice" name="deal[12][2]"></td>
</tr>
<tr>
<td class="tg-amwm" colspan="2">Total</td>
<td class="tg-0lax"><span id="totalDeal">0</span></td>
</tr>
</tbody>
</table>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
You have to put the getItemPrice inside of the function of where you get its checked. Please check the following code:
$(function() {
$('.dealprice').on('input', function(){
var eachPrice = 0;
$('.dealprice:checkbox:checked').each(function(){
const getItemPrice = $(this).closest("tr").find('input[name=itemprice]').val();
eachPrice += isNaN(parseInt(getItemPrice)) ? 0 : parseInt(getItemPrice);
});
$("#totalDeal").text(eachPrice.toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,'));
});
});
Also check this repl https://repl.it/repls/LavenderAgonizingRoot

Dynamic table if checkbox is unchekd empty() the td cell with JS

I have dynamic table that in one td passes php vales of prices and on end of the table is sum of those prices. There is also a checkbox in every row default checked. I need to empty the content of row where checkbox is unchecked so it removes that price value out of sum calculation.
Question, will that even remove that value? I know setting the td field to hide does not.
Value cell:
<td style="width:10%" class="rowDataSd" id="value">
<?php echo
str_replace(array(".", ",",), array("", "."), $row['rad_iznos']);
?>
</td>
Checkbox cell:
<td style="width:3%">
<input class="w3-check" type="checkbox" checked="checked" id="remove" name="uvrsti" value="<?php echo $row['rad_id']?>">
</td>
I tried with this but nothing happens with no errors:
$(document).ready(function(){
if($("#remove").is(':checked')) {
$("#value").show();
} else {
$("#value").empty();
}
});
I can pass the unique values into each checkbox and value element into id's like:
id="<?php echo $row['rad_id']?>"
. So they tie each other but don't know how to say in JS to empty those elements.
I was also thinking something along the lines of, if on some row checkbox is unchecked empty closest td with id="value". My guess is that would be best solution but I don't know how to write it.
Or even if checkbox is unchecked remove css class .rowDataSd to closest td with id="vale" based on whom calculation is made.
Sum script:
var totals=[0,0,0];
$(document).ready(function(){
var $dataRows=$("#sum_table tr:not('.totalColumn, .titlerow')");
$dataRows.each(function() {
$(this).find('.rowDataSd').each(function(i){
totals[i]+=parseFloat( $(this).html());
});
});
$("#sum_table td.totalCol").each(function(i){
$(this).html('<span style="font-weight: bold;text-shadow: 0.5px 0 #888888;">'+totals[i].toFixed(2)+' kn</span>');
});
});
As seen on picture need to remove row out of calculation if checkbox is unchecked. Keep in mind I dont want to delete to row, just remove it our of calculation.
Any help with how to approach this is appreciated.
Here is a basic example.
$(function() {
function getPrice(row) {
var txt = $(".price", row).text().slice(1);
var p = parseFloat(txt);
return p;
}
function calcSum(t) {
var result = 0.00;
$("tbody tr", t).each(function(i, r) {
if ($("input", r).is(":checked")) {
result += getPrice(r);
}
});
return result;
}
function updateSum(tbl) {
var t = calcSum(tbl);
$("tfoot .total.price", tbl).html("$" + t.toFixed(2));
}
updateSum($("#price-list"));
$("#price-list input").change(function() {
updateSum($("#price-list"));
});
});
#price-list {
width: 240px;
}
#price-list thead th {
width: 33%;
border-bottom: 1px solid #ccc;
}
#price-list tfoot td {
border-top: 1px solid #ccc;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="price-list">
<thead>
<tr>
<th>Name</th>
<th>Price</th>
<th> </th>
</tr>
</thead>
<tbody>
<tr>
<td class="item name">Item 1</td>
<td class="item price">$3.00</td>
<td><input type="checkbox" checked /></td>
</tr>
<tr>
<td class="item name">Item 2</td>
<td class="item price">$4.00</td>
<td><input type="checkbox" checked /></td>
</tr>
<tr>
<td class="item name">Item 3</td>
<td class="item price">$5.00</td>
<td><input type="checkbox" checked /></td>
</tr>
</tbody>
<tfoot>
<tr>
<td>Sum</td>
<td class="total price">$0.00</td>
<td> </td>
</tr>
</tfoot>
</table>
It all boils down to setting up an event handler for the checkboxes. The event handler should perform the following:
Track the checkbox change event for all checkboxes and the DOM ready event
Calculate the total of all rows with checkbox checked
Set the total to the total element
It call also perform any desired changes on the unchecked row .. not done in sample code below
THE CODE
$(function() {
$('.select').on('change', function() {
let total = $('.select:checked').map(function() {
return +$(this).parent().prev().text();
})
.get()
.reduce(function(sum, price) {
return sum + price;
});
$('#total').text( total );
})
.change();//trigger the change event on DOM ready
});
THE SNIPPET
$(function() {
$('.select').on('change', function() {
let total = $('.select:checked').map(function() {
return +$(this).parent().prev().text();
})
.get()
.reduce(function(sum, price) {
return sum + price;
});
$('#total').text( total );
})
.change();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<thead>
<tr>
<th>Item</th>
<th>Price</th>
<th>Select</th>
</tr>
</thead>
<tbody>
<tr>
<td>Item 1</td>
<td>1000</td>
<td><input type="checkbox" class="select" checked></td>
</tr>
<tr>
<td>Item 2</td>
<td>1200</td>
<td><input type="checkbox" class="select" checked></td>
</tr>
<tr>
<td>Item 3</td>
<td>800</td>
<td><input type="checkbox" class="select" checked></td>
</tr>
<tr>
<td>Item 4</td>
<td>102000</td>
<td><input type="checkbox" class="select" checked></td>
</tr>
</tbody>
</table>
<span>TOTAL</span><span id="total"></span>

How do I uncheck 'select-all' checkbox if any child checkbox gets unchecked

I have provided the code which on click select-all checkbox , child
checkbox gets checked/unchecked. Now if I deselect any child checkbox ,
'select-all' checkbox should get unchecked. How do I do?
$(document).ready(function() {
$('#select-all').click(function(event) {
var $that = $(this);
$(':checkbox').each(function() {
this.checked = $that.is(':checked');
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="select" style="margin-top:54px; margin-left:10px; margin-right:10px;">
<table class="w3-table-all w3-centered w3-hoverable">
<tr class="w3-gray" style="width:100%">
<th style="padding:20px;"><input id="select-all" class="w3-check w3-left" type="checkbox"><span style="padding:20px;">User name</span></th>
<th style="padding:15px;">User Id</th>
<th style="padding:15px;">Designation</th>
<th style="padding:15px;">Phone No</th>
<th style="padding:15px;">Address</th>
</tr>
<tr>
<td style="padding:20px;"><input class="w3-check w3-left" type="checkbox"><span style="padding:20px;">mandeep kumbhar</span></td>
<td style="padding:20px">employee#123</td>
<td style="padding:20px">security Incharge</td>
<td style="padding:20px">123456789</td>
<td style="padding:20px">18/522,Neelkanth CHS,Nehru Nagar,Kurla East,Mumbai-400024</td>
</tr>
<tr>
<td style="padding:20px;"><input class="w3-check w3-left" type="checkbox"><span style="padding:20px;">mandeep kumbhar</span></td>
<td style="padding:20px">employee#123</td>
<td style="padding:20px">security Incharge</td>
<td style="padding:20px">123456789</td>
<td style="padding:20px">awtry lbduyvetyd jhvdytf ihuusb</td>
</tr>
<tr>
<td style="padding:20px;"><input class="w3-check w3-left" type="checkbox"><span style="padding:20px;">mandeep kumbhar</span></td>
<td style="padding:20px">employee#123</td>
<td style="padding:20px">security Incharge</td>
<td style="padding:20px">123456789</td>
<td style="padding:20px">awtry lbduyvetyd jhvdytf ihuusb</td>
</tr>
</table>
</div>
To uncheck select-all when user uncheck any checkbox try below code.
$('.checkbox').click(function(){
if($(this).prop("checked") == false){
$('#select-all').prop('checked', false);
}
}
You can give class for child checkbox and check condition for checked unchecked.
$('#checkall').on('change', function() {
$('.test:checkbox').prop('checked', $(this).is(":checked"));
});
$('.test').on('change', function() {
if (!$(this).is(':checked')) {
$('.test').prop('checked', false);
$('#checkall').prop('checked', false);
}
if ($('.test:checked').length === 1) {
$('.test').prop('checked', false);
$('#checkall').prop('checked', false);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="checkall" />Check all
<input type="checkbox" class="test" />1
<input type="checkbox" class="test" />2
<input type="checkbox" class="test" />3
<input type="checkbox" class="test" />4
Do your stuff in on change of child checkbox.
$('.checkbox').change(function(){
if($(this).prop("checked") == false){
$('#select-all').prop('checked', false);
}
}
I'd suggest the following, which allows the #select-all element to check all the 'child' check-boxes, and allows those child check-boxes to check, or uncheck, the #select-all:
// caching the <table> element:
var tableElement = $('table');
// binding the anonymous function of the on() method to the
// 'change' event that takes place on <input> elements of
// type=checkbox:
tableElement.on('change', 'input[type=checkbox]', function(event) {
// caching the changed element:
var changed = event.target,
// caching:
checkboxes = tableElement
// <input> elements within the <table>
// of type=checkbox:
.find('input[type=checkbox]')
// which do not match the '#select-all'
// selector:
.not('#select-all');
// if the changed element has the id of 'select-all':
if (changed.id === 'select-all') {
// we update the 'checked' property of the cached
// check-box inputs to reflect the checked state
// of the '#select-all' element:
checkboxes.prop('checked', changed.checked);
} else {
// here we check that the number of checked checkboxes
// is equal to the number of check-boxes (effectively
// finding out whether all, or not-all, check-boxes are
// checked:
var allChecked = checkboxes.length === checkboxes.filter(':checked').length
// here we update the 'checked' property of the
// '#select-all' check-box to true (if the
// number of checked check-boxes is equal to the
// number of check-boxes) or false (if the number
// of checked check-boxes is not equal to the
// number of check-boxes):
$('#select-all').prop(
'checked', allChecked
);
}
});
var tableElement = $('table');
tableElement.on('change', 'input[type=checkbox]', function(event) {
var changed = event.target,
checkboxes = tableElement
.find('input[type=checkbox]')
.not('#select-all');
if (changed.id === 'select-all') {
checkboxes.prop('checked', changed.checked)
} else {
var allChecked = checkboxes.length === checkboxes.filter(':checked').length
$('#select-all').prop(
'checked', allChecked
);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="select" style="margin-top:54px; margin-left:10px; margin-right:10px;">
<table class="w3-table-all w3-centered w3-hoverable">
<tr class="w3-gray" style="width:100%">
<th>
<input id="select-all" class="w3-check w3-left" type="checkbox">
<span>User name</span></th>
<th>User Id</th>
<th>Designation</th>
<th>Phone No</th>
<th>Address</th>
</tr>
<tr>
<td>
<input class="w3-check w3-left" type="checkbox">
<span>mandeep kumbhar</span></td>
<td>employee#123</td>
<td>security Incharge</td>
<td>123456789</td>
<td>18/522,Neelkanth CHS,Nehru Nagar,Kurla East,Mumbai-400024</td>
</tr>
<tr>
<td>
<input class="w3-check w3-left" type="checkbox">
<span>mandeep kumbhar</span></td>
<td>employee#123</td>
<td>security Incharge</td>
<td>123456789</td>
<td>awtry lbduyvetyd jhvdytf ihuusb</td>
</tr>
<tr>
<td>
<input class="w3-check w3-left" type="checkbox">
<span>mandeep kumbhar</span></td>
<td>employee#123</td>
<td>security Incharge</td>
<td>123456789</td>
<td>awtry lbduyvetyd jhvdytf ihuusb</td>
</tr>
</table>
</div>
JS Fiddle demo.
If, however, you'd prefer to do this in plain JavaScript:
// a named, rather than anonymous, function to handle
// the functionality, passing in the event Object:
function checkToggle(event) {
// caching the changed element:
var changed = event.target,
// caching the element with the id of 'select-all':
selectAll = document.getElementById('select-all'),
// caching all <input> elements of type=checkbox,
// using Function.prototype.call() to apply
// Array.prototype.slice() to the HTMLCollection
// returned by document.querySelectorAll(), in order
// to convert the Array-like HTMLCollection into an
// Array:
checkboxes = Array.prototype.slice.call(
this.querySelectorAll('input[type=checkbox]')
// filtering the Array of <input> elements:
).filter(function(check) {
// retaining only those <input> elements which are
// not the selectAll element:
return check !== selectAll;
});
// if the changed element is the selectAll element:
if (changed === selectAll) {
// we iterate over the Array of checkboxes using
// Array.prototype.forEach():
checkboxes.forEach(function(check) {
// 'check' is a reference to the current
// check-box in the Array of check-boxes;
// and here we update the checked property
// of each <input> to reflect the state of
// the selectAll <input>:
check.checked = selectAll.checked;
});
} else {
// filtering the array of checkboxes to retain only
// those that are checked:
var allChecked = checkboxes.filter(function(check) {
return check.checked;
// retrieving the length of the filtered Array and
// comparing that length to the length of the Array
// check-boxes in total:
}).length === checkboxes.length;
// updating the 'checked' property of the selectAll
// element to true (if all 'child' checkboxes are
// checked) or false (if not all 'child' checkboxes
// are checked):
selectAll.checked = allChecked;
}
}
var tableElement = document.querySelector('table');
tableElement.addEventListener('change', checkToggle);
function checkToggle(event) {
var changed = event.target,
selectAll = document.getElementById('select-all'),
checkboxes = Array.prototype.slice.call(
this.querySelectorAll('input[type=checkbox]')
).filter(function(check) {
return check !== selectAll;
});
if (changed === selectAll) {
checkboxes.forEach(function(check) {
check.checked = selectAll.checked;
});
} else {
var allChecked = checkboxes.filter(function(check) {
return check.checked;
}).length === checkboxes.length;
selectAll.checked = allChecked;
}
}
var tableElement = document.querySelector('table');
tableElement.addEventListener('change', checkToggle);
<div id="select" style="margin-top:54px; margin-left:10px; margin-right:10px;">
<table class="w3-table-all w3-centered w3-hoverable">
<tr class="w3-gray" style="width:100%">
<th>
<input id="select-all" class="w3-check w3-left" type="checkbox">
<span>User name</span></th>
<th>User Id</th>
<th>Designation</th>
<th>Phone No</th>
<th>Address</th>
</tr>
<tr>
<td>
<input class="w3-check w3-left" type="checkbox">
<span>mandeep kumbhar</span></td>
<td>employee#123</td>
<td>security Incharge</td>
<td>123456789</td>
<td>18/522,Neelkanth CHS,Nehru Nagar,Kurla East,Mumbai-400024</td>
</tr>
<tr>
<td>
<input class="w3-check w3-left" type="checkbox">
<span>mandeep kumbhar</span></td>
<td>employee#123</td>
<td>security Incharge</td>
<td>123456789</td>
<td>awtry lbduyvetyd jhvdytf ihuusb</td>
</tr>
<tr>
<td>
<input class="w3-check w3-left" type="checkbox">
<span>mandeep kumbhar</span></td>
<td>employee#123</td>
<td>security Incharge</td>
<td>123456789</td>
<td>awtry lbduyvetyd jhvdytf ihuusb</td>
</tr>
</table>
</div>
JS Fiddle demo.
References:
JavaScript:
Array.prototype.filter().
Array.prototype.forEach().
Array.prototype.slice().
document.getElementById().
document.querySelectorAll().
Event Object.
EventTarget.addEventListener().
Function.prototype.call().
jQuery:
filter().
find().
not().
on().
prop().

delete button visible while checkbox is checked

I have table with 3 columns. The third columns is a check box for each row.
<tr id='sub".$this->getHtmlId()."_".$cpt."' class='mui-row'>
<td class='mui-col-md-6'>".$row[0]."</td>
<td class='mui-col-md-2'>".$row[1]."</td>
<td class='mui-col-md-2' style='border:none'>
<component id='box' class=\ "CheckBoxComponent\" name=\ "chk".$row[3]. "\" />
</td>
</tr>";
what i want is that when I check a checkbox the delete button become visible and if i check a second or more it stay visible because I can delete multiple rows at the same time.
Right now, everything I have tried do that when I check a row the button appear I click a second one it disappear and when I click a third one it appear again
here some example that I tried :
$('#deleteButton').toggle('slow', function() {
// Animation complete.
});
var chkbox = $(\".check\");
button = $(\"#box\");
button.attr(\"disabled\",\"disabled\");
chkbox.change(function() {
if (this.checked) {
button.removeAttr(\"disabled\");
}
else {
button.attr(\"disabled\",\"disabled\");
}
});
You can get the count of checked checkbox by $(".check:checked").length
If there is a checked checkbox, show the button.
$(function() {
//hide on init
$("#deleteButton").hide();
$(".check").click(function() {
//get the number of checked
if ($(".check:checked").length) $("#deleteButton").show();
else $("#deleteButton").hide();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr class='mui-row'>
<td class='mui-col-md-6'>1</td>
<td class='mui-col-md-2'>1</td>
<td class='mui-col-md-2' style='border:none'>
<input type="checkbox" class="check">
</td>
</tr>
<tr class='mui-row'>
<td class='mui-col-md-6'>2</td>
<td class='mui-col-md-2'>2</td>
<td class='mui-col-md-2' style='border:none'>
<input type="checkbox" class="check">
</td>
</tr>
<tr class='mui-row'>
<td class='mui-col-md-6'>3</td>
<td class='mui-col-md-2'>3</td>
<td class='mui-col-md-2' style='border:none'>
<input type="checkbox" class="check">
</td>
</tr>
</table>
<button id="deleteButton" type="button">Delete!</button>

Toggle display of input based on radio button selection individually for cells in column

I replaced the contents of all cells in a column of an HTML table with radio buttons and a text input. The text input should only display if the radio button selected for that row is "rejected".
Currently, my code is:
$(document).ready(function() {
var $table = $("table.tables.list");
if ($table.length > 0) {
var qc_statusTh = $("th.headersub:contains('QC Status')");
var qc_statusColumnIndex = $(qc_statusTh).index();
var qc_statusRows = $($table).find('tr');
$(qc_statusRows).each(function() {
$(this).find('td').eq(qc_statusColumnIndex).replaceWith("<td class='sub'><div class='radio-form'><form action=''><input type='radio' name='qc-status' value='approved'> Approved<br><input type='radio' name='qc-status' value='rejected'> Rejected<input style='display:none;' type='text' name='qc-status' class='qc-status-text'/></form></div></td>");
});
$("input[type='radio']").change(function() {
if ($(this).val() == "rejected") {
$(".qc-status-text").show();
} else {
$(".qc-status-text").hide();
}
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="tables list">
<thead>
<th class="headersub">qc_example</th>
<th class="headersub">qc_status</th>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Ok</td>
</tr>
<tr>
<td>2</td>
<td>Ok</td>
</tr>
<tr>
<td>3</td>
<td>Error</td>
</tr>
</tbody>
</table>
If you run this code, when you select "rejected" with the radio buttons, the text input will display in every cell in that column. I need the text input to display on an individual basis per row. How can I accomplish this?
Note: The reason this needs to be done in this wonky/hacky way is because of the system we are using. Not by choice :)
You could use siblings() method to select the related input with the current changed radio button, like :
if ($(this).val() == "rejected") {
$(this).siblings(".qc-status-text").show();
}else{
$(this).siblings(".qc-status-text").hide();
}
Hope this helps.
$(document).ready(function() {
var $table = $("table.tables.list");
if ($table.length > 0) {
var qc_statusTh = $("th.headersub:contains('QC Status')");
var qc_statusColumnIndex = $(qc_statusTh).index();
var qc_statusRows = $($table).find('tr');
$(qc_statusRows).each(function() {
$(this).find('td').eq(qc_statusColumnIndex).replaceWith("<td class='sub'><div class='radio-form'><form action=''><input type='radio' name='qc-status' value='approved'> Approved<br><input type='radio' name='qc-status' value='rejected'> Rejected<input style='display:none;' type='text' name='qc-status' class='qc-status-text'/></form></div></td>");
});
$("input[type='radio']").change(function() {
if ($(this).val() == "rejected") {
$(this).siblings(".qc-status-text").show();
}else{
$(this).siblings(".qc-status-text").hide();
}
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="tables list">
<thead>
<th class="headersub">qc_example</th>
<th class="headersub">qc_status</th>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Ok</td>
</tr>
<tr>
<td>2</td>
<td>Ok</td>
</tr>
<tr>
<td>3</td>
<td>Error</td>
</tr>
</tbody>
</table>
$(document).ready(function() {
var $table = $("table.tables.list");
$table.find('td:odd').replaceWith("<td class='sub'><div class='radio-form'><form action=''><input type='radio' name='qc-status' value='approved'> Approved<br><input type='radio' name='qc-status' value='rejected'> Rejected<input style='display:none;' type='text' name='qc-status' class='qc-status-text'/></form></div></td>");
$("input[type='radio']").change(function() {
$(".qc-status-text", $(this).parent()).toggle(this.value=="rejected");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="tables list">
<thead>
<th class="headersub">qc_example</th>
<th class="headersub">qc_status</th>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Ok</td>
</tr>
<tr>
<td>2</td>
<td>Ok</td>
</tr>
<tr>
<td>3</td>
<td>Error</td>
</tr>
</tbody>
</table>

Categories

Resources