How can I check a checkbox depending on what row using jQuery? - javascript

What I have tried is to make a checkbox when clicked it automatically checks the other checkbox from it's row but when I tried to check the other rows, it does not work. I've tried to make a loop but instead of checking each, it checks all. I hope someone can help me. Thank you so much in advance!
Here is my whole code, I am using dataTables
$(document).ready(function() {
$('#is_checked_status').on('click', function() {
var checkAll = this.checked;
$('input[id=subCheckbox]').each(function() {
this.checked = checkAll;
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="row">
<div class="col-lg-12">
<div class="panel panel-default">
<div class="panel-heading">
Emailed Data for approval
</div>
<!-- /.panel-heading -->
<div class="panel-body">
<div class="table-responsive">
<table width="100%" class="table table-striped table-bordered table-hover" id="dataTables">
<thead>
<tr>
<th> Control Number </th>
<th> Tools Specification </th>
<th> Supplier </th>
<th>
<center> Status </center>
</th>
<th>
<center> Select data to approve </center>
</th>
<th>
<center> ID </center>
</th>
</tr>
</thead>
<?php
$con->next_result();
$result = mysqli_query($con,"CALL GetAllRequestedTools()"); ?>
<tbody>
<?php
while ($row = mysqli_fetch_assoc($result))
{
echo "<tr>";
echo "<td><a href='edit_tools_approval.php?
ID=".$row['ID']."' style='color:red;'>" .
$row['reg_input'] . "</a></td>";
echo "<td>" . $row['reg_tools_spec'] . "</td>";
echo "<td>" . $row['reg_supplier'] . "</td>";
?>
<td>
<center>
<label data-id="<?php echo $row['ID'];?>" class="statusButton <?php echo ($row['req_stats'])? 'label-success': 'label-danger'?>">
<?php echo ($row['req_stats'])? 'Approved' : 'Pending'?>
</label>
</center>
</td>
<td>
<center>
<input name="chk_status[]" id="is_checked_status" type="checkbox" value="<?php echo $row['req_stats'];?>">
</center>
</td>
<td>
<center>
<input name="chk_id[]" type="checkbox" id="subCheckbox" value="<?php echo $row['ID'];?>">
</center>
</td>
<?php
echo "</tr>";
}
?>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>

Ids are singular so you can not use an id multiple times. Change all of the ids to a class.
After you remove the ids and swap it to a class. You will need find the row the checkbox is in. And then select all the checkboxes in that row.
$(document).ready(function() {
$('.is_checked_status').on('click', function() {
var checkAll = this.checked;
// find the row
var row = $(this).closest("tr");
// find the checkboxes in the row
row.find('input.subCheckbox').each(function() {
this.checked = checkAll;
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<td><input type="checkbox" class="is_checked_status" /></td>
<td><input type="checkbox" class="subCheckbox" /></td>
<td><input type="checkbox" class="subCheckbox" /></td>
<td><input type="checkbox" class="subCheckbox" /></td>
<td><input type="checkbox" class="subCheckbox" /></td>
</tr>
<tr>
<td><input type="checkbox" class="is_checked_status" /></td>
<td><input type="checkbox" class="subCheckbox" /></td>
<td><input type="checkbox" class="subCheckbox" /></td>
<td><input type="checkbox" class="subCheckbox" /></td>
<td><input type="checkbox" class="subCheckbox" /></td>
</tr>
</table>

Related

How to click one checkbox that shows 2 specific columns in a table

I have a table linked to my SQL. I want to use checkboxes that on click shows only 2 specific columns from the table.
Example: When clicking on salary checkbox, salary_column and extension_column should appear.
I have only made it work with only one column to display
I have tried the following:
$(function(){
$(':checkbox').on('change', function(){
$('th, td', 'tr').filter(':nth-child(' + $(this).data('col') + ')').toggle();
$('td:nth-child(2),th:nth-child(2)').show();
$('td:nth-child(3),th:nth-child(3)').show();
});
});
<input type="checkbox" data-col="2" class="example" checked="false" /> Salary
<input type="checkbox" data-col="3" class="example" checked="false" /> Position
<input type="checkbox" data-col="4" class="example" checked="false" /> City
<input type="checkbox" data-col="5" class="example" checked="false" /> Ext
<input type="checkbox" data-col="6" class="example" checked="false" /> Joined Date
<input type="checkbox" data-col="7" class="example" checked="false" /> Age
<input id="btnHide" onclick="uncheckAll2()" type="button" value="CEAR ALL"/>
<table id="employee-grid" class="w3-table-all cellspacing="0" width="100%">
<thead>
<tr>
<th class="employee_name" >Name</th>
<th class="employee_salary" >Salary</th>
<th class="employee_position">Position</th>
<th class="employee_city">City</th>
<th class="employee_extension">Ext</th>
<th class="employee_joining_date">Joined</th>
<th class="employee_age">Age</th>
</tr>
</thead>
<tbody>
<?php
$db = new PDO("mysql:host=localhost;dbname=test","root","");
$stmt = $db->prepare("select * from employee");
$stmt->execute();
while($row = $stmt->fetch()){
?>
<tr>
<td><?php echo $row['employee_name'] ?> </td>
<td id="sal"><?php echo $row['employee_salary'] ?> </td>
<td id="pos"><?php echo $row['employee_position'] ?></td>
<td id="cit"><?php echo $row['employee_city'] ?></td>
<td id="exts"><?php echo $row['employee_extension'] ?></td>
<td id="jdat"><?php echo $row['employee_joining_date'] ?></td>
<td id="agi"><?php echo $row['employee_age'] ?></td>
</tr>
<?php
}
?>
</tbody>
</table>
<script>
$(function(){
$(':checkbox').on('change', function(){
$('th, td', 'tr').filter(':nth-child(' + $(this).data('col') + ')').toggle();
});
});
</script>
Trying to make it like this:
https://i.ibb.co/8XTv2gc/Untitled.jpg
My idea is... each checkbox has reference to <th> (column to show/hide). I use data-target with jquery selector as the values.
<input type="checkbox" data-target=".employee_salary, .employee_extension" checked /> Salary
<input type="checkbox" data-target=".employee_position" checked /> Position
<input type="checkbox" data-target=".employee_city" checked /> City
<input type="checkbox" data-target=".employee_joining_date" checked /> Joined Date
<input type="checkbox" data-target=".employee_age" checked /> Age
By using jQuery, get the n-th position of each <th>. After that, iterate all rows and show/hide n-th column.
$(function() {
$(':checkbox').on('change', function() {
var $checkbox = $(this);
var state = $checkbox.prop('checked'); // true -> show, false -> hide
// iterate all <th> referenced by <input data-target="">
$($checkbox.data('target')).each(function() {
var index = $(this).index(); // get its n-th position
// iterate all rows, show/hide the n-th column
$('table tr').each(function() {
if (state) {
$(this).find('th:eq(' + index + ')').show();
$(this).find('td:eq(' + index + ')').show();
} else {
$(this).find('th:eq(' + index + ')').hide();
$(this).find('td:eq(' + index + ')').hide();
}
});
});
});
});

trying to allow an empty row to the bottom of a input table using JavaScript

I am trying to create a form where the user can click on a button that will create a blank row at the bottom of the table. They can click this button for as many rows as they want to add. For some reason, when I click on the button I created, it goes back to my index.php page instead of just adding the row to the current page. Here is some of the code. Please let me know if there is more information that I should be adding here.
Thank you
JavaScript:
function new_line() {
var t = document.getElementById("desc_table");
var rows = t.getElementsByTagName("tr");
var r = rows[rows.length - 1];
var x = rows[1].cloneNode(true);
x.style.display = "";
r.parentNode.insertBefore(x, r);
}
<?php include 'connect.php'; ?>
<!DOCTYPE xhtml>
<html>
<head>
<style type="text/css"><?php //include'css\file.css';?></style>
<script type="text/javascript" src="js/new_line.js"></script>
<script type="text/javascript" src="js/menu.js"></script>
<body>
<button id="home" onclick="home_btn()">Home</button>
<title>New Estimate</title>
<h1>New Estimate</h1>
<?php
$sql = $conn->prepare('SELECT * FROM entire_info');
$sql -> execute();
$result = $sql ->get_result();
if ($result->num_rows!=0) {
$entire_info=$result->fetch_assoc();
}
else{
echo'Cannot find company information<br>';
}
?>
<form>
<table id="estimate_table">
<tr>
<td>
<?php
echo '<h1>'.$entire_info['name'].'</h1><br>'.
$entire_info['str_address'].'<br>'.
$entire_info['city'].', '.$entire_info['province'].' '.$entire_info['postal']
.'<br>Phone:'.$entire_info['phone'].'<br>Fax:'.$entire_info['fax'].'<br>'.$entire_info['email'].'<br>';
?>
<br>
</td>
<td colspan="3" style="text-align: right;"><?php echo '<h1>Estimate</h1>'; ?></td>
</tr>
<tr>
<td>
<table>
<tr>
<td style="vertical-align: top;">
For:<br>
<select name="estimate_for">
<?php
$sql = $conn->prepare('SELECT * FROM company');
$sql -> execute();
$result = $sql ->get_result();
if ($result->num_rows>0) {
while ($row=$result->fetch_assoc()) {
$company_name = $row['company'];
echo '<option value="'.$company_name.'">'.$company_name.'</option>';
}
}
else{
echo'Cannot find company information<br>';
}
?>
</select>
</td>
<td>
Job:<br> <textarea name="job_name" style="width: 200px ! important;" style="height: 30px ! important;"></textarea>
</td>
</tr>
</table>
</td>
<td colspan="3" style="text-align: right;">
Invoice#: <br>
Date: <input type="text" name="estimate_date" value="<?php echo date('M d, Y'); ?>">
</td>
</tr>
</table>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
<table id="desc_table">
<tr>
<td><font><br><h3>Description</h3></font></td>
<td><font><h3>Hours</h3></font></td>
<td><font><h3>Rate</h3></font></td>
<td><font><h3>Amount</h3></font></td>
</tr>
<tr>
<td ><textarea name="description" style="width: 400px" style="height: 100px ! important;"></textarea></td>
<td> <input type="text" name="hours"></td>
<td> <input type="text" name="rate"></td>
<td><input type="text" name="amount"></td>
<td>
<button onclick="new_line();">+</button>
</td>
</tr>
<tr>
<td colspan="3" style="text-align: right;"><h3>Subtotal</h3></td>
<td><input type="text" name="subtotal"></td>
</tr>
<tr>
<td colspan="3" style="text-align: right;"><h3>GST (#87221 2410)
</h3></td>
<td><input type="text" name="gst"></td>
</tr>
<tr>
<td colspan="3" style="text-align: right;"><h3>Total</h3></td>
<td><input type="text" name="subtotal"></td>
</tr>
</table>
</form>
</head>
</body>
</html>
Your button is inside a <form> so by default it will behave like a submit button.
You have to set its type to a normal button by adding the type attribute:
<button onclick="new_line();" type="button">+</button>

Add Row Button adds PHP cell with Select2 option

Sorry about the Q form but I couldn't find a better way to explain it.
I have a view table that have drop down form that retrieves its options from the DB to be inserted, and it have an add button to add new row to insert.
But the drop down works on Select2 forms, and it's included in the table, so every time I try to add new row it gives it the same id as the previous one and that conflicts with the JS for the Select2 as it needs to get special id for every drop down I made with it.
here's the table and the add button code
<div class="row">
<div class="table-responsive">
<table class="table table-bordered" id="tab_logic">
<thead>
<tr>
<th>Brand Name</th>
<th>Item Name</th>
<th>Model Number</th>
<th class="col-md-2">Item Description</th>
<th>Part Number</th>
<th>Unit</th>
<th class="col-md-1">QTY</th>
<th class="col-md-1">Unit Price (SR)</th>
<th class="col-md-1">Total Price (SR)</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<strong>Record</strong>
</td>
<td>
<strong>Record</strong>
</td>
<td>
<strong>Record</strong>
</td>
<td>
<div class="form-group">
<?php
$query = $con->query("SELECT products_itemDescription FROM pruc_products"); // Run your query --> For Item Desc.
echo '<select class="form-control" id="DescriptionS2forms" name="itemDescription">'; // Open your drop down box
echo '<option value="" selected="selected" disabled></option>'; //Empty Value for VALIDATION
// Loop through the query results, outputing the options one by one
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
echo '<option value="'.$row['products_itemDescription'].'">'.$row['products_itemDescription'].'</option>';
}
echo '</select>';// Close your drop down box
?>
</div>
</td>
<td>
<strong>Record</strong>
</td>
<td>
<strong>Record</strong>
</td>
<td>
<div>
<input class="form-control" type="number" name="requestQTY" required>
</div>
</td>
<td>
<div>
<input class="form-control" type="number" name="requestUnit" step="0.01" min="0.01" max="1000000" required>
</div>
</td>
<td>
<strong>Record</strong>
</td>
<td class="col-md-1" id="deleteBtn">
<a class="btn btn-default deleteBtn">Delete</a>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<!-- End of 3rd Row -->
<div class="row">
<a id="add_row" class="btn btn-default pull-right">Add</a>
</div>
And the JS for the add button and select2 function:
$(document).ready(function() {
var i = 0;
$("#add_row").click(function() {
var x = '[{<td><strong>Record</strong></td> <td><strong>Record</strong></td> <td><strong>Record</strong></td> <td><div class="form-group"> <?php $query = $con->query('SELECT products_itemDescription FROM pruc_products'); echo '<select class="form-control" id=DescriptionS2forms'.(i+1).'" name="itemDescription">'; echo '<option value="" selected="selected" disabled></option>'; while($row = $query->fetch(PDO::FETCH_ASSOC)) {echo '<option value="'.$row['products_itemDescription'].'">'.$row['products_itemDescription'].'</option>';} echo '</select>'; ?> </div></td> <td><strong>Record</strong></td> <td><strong>Record</strong></td> <td><div><input class="form-control" type="number" name="requestQTY" required></div></td> <td><div><input class="form-control" type="number" name="requestUnit" step="0.01" min="0.01" max="1000000" required></div></td> <td><strong>Record</strong></td> <td class="col-md-1" id="deleteBtn"> <a class="btn btn-default deleteBtn">Delete</a></td>}]';
$('#tab_logic').append('<tr id="addr' + (i + 1) + '">' + x + '</tr>');
i++;
});
$("#SupplierS2forms, #ProjectS2forms, #WHS2forms, #DescriptionS2forms").select2(); });
in the PHP option it gives the id="DescriptionS2forms"
so I need to add a number for the id so I can use it in the Select2 Function as it doesn't accept same id
Example
id="DescriptionS2forms1" AND id="DescriptionS2forms2"

How to get the value in Textbox from database depends on dropdown list without submit button

I want to get the text box value from database depends upon the dropdownlist values without using submit button .Now I have three dropdown list on my code.how can i write the javascript for three dropdown
<div align="center">
<table>
<thead>
<th>Product</th>
<th>Quantity</th>
<th>Rate</th>
<th>Amount</th>
</thead>
<tbody>
<tr id="addrow">
<td>
<?php
$selectproduct=mysql_query("select productname from items");
$itemname=mysql_fetch_array($selectproduct);
?>
<select name="item[]" id="item">
<?php
$i=0;
while($itemname=mysql_fetch_array($selectproduct))
{
?>
<option value="<?php echo $itemname['productname'];?>"><?php echo $itemname['productname'];?></option>
<?php
$i++;
}
?>
</td>
<?php
// $amount=mysql_query("select Amount from items where Productname='$productname' ");
// $totalamount=mysql_fetch_array($amount);
?>
<td><input class="qty" type="text" name="qty[]"></td>
<td><input class="price" type="text" name="price[]"></td>
<td><input type="text" class="output" name="output[]"></td>
</tr>
<tr >
<td>
<?php
$selectproduct=mysql_query("select productname from items");
$itemname=mysql_fetch_array($selectproduct);
?>
<select name="item[]" id="item">
<?php
$i=0;
while($itemname=mysql_fetch_array($selectproduct))
{
?>
<option value="<?php echo $itemname['productname'];?>"><?php echo $itemname['productname'];?></option>
<?php
$i++;
}
?>
</td>
<td><input class="qty" type="text" name="qty[]"></td>
<td><input class="price" type="text" name="price[]"></td>
<td><input type="text" class="output" name="output[]"></td>
</tr>
<tr>
<td>
<?php
$selectproduct=mysql_query("select productname from items");
$itemname=mysql_fetch_array($selectproduct);
?>
<select name="item[]" id="item">
<?php
$i=0;
while($itemname=mysql_fetch_array($selectproduct))
{
?>
<option value="<?php echo $itemname['productname'];?>"><?php echo $itemname['productname'];?></option>
<?php
$i++;
}
?>
</td>
<td><input class="qty" type="text" name="qty[]"></td>
<td><input class="price" type="text" name="price[]"></td>
<td><input type="text" class="output" name="output[]"></td>
</tr>
</table>
<div id="grand">
Total Amount:<input type="text" name="gran" id="gran">
</div>
</tr>
<tr >
<td colspan="4">
<center><input type="submit" name="submit"></center>
</td>
</tr>
</tbody>
</table>
</div>
</form>
</body>
<script type="text/javascript">
$(document).ready(function() {
$(".price").keyup(function() {
var grandTotal = 0;
$("input[name='qty[]']").each(function (index) {
var qty = $("input[name='qty[]']").eq(index).val();
var price = $("input[name='price[]']").eq(index).val();
var output = parseInt(qty) * parseInt(price);
if (!isNaN(output)) {
$("input[name='output[]']").eq(index).val(output);
grandTotal = parseInt(grandTotal) + parseInt(output);
$('#gran').val(grandTotal);
}
});
});
});
</script>
I recommand you to use jQuery for start. It is easier to manipulate the DOM.
Follow a tutorial and then, attach a callback on the change event on your dropdown menus, then in the callback get the values for your menu in an ajax call, then generate the html (the option tags) and update your select.
The Ajax call and the html update can be done with jQuery, but you can do it by yourself in pure Javascript as well.
You'll need to use AJAX calls from JS. AJAX has to send and receive data from php script. Simple AJAX tutorial: https://www.w3schools.com/js/js_ajax_php.asp

Checkbox in a dynamic table with dynamic input fields

I have a table with dynamic values and hidden input fields and dynamic checkbox. Checkboxes have same class names. When i click on a particular checkbox i want the input values from that particluar row should be sent to ajax.
Below is the code for dynamic table,
<table id="table">
<thead>
<tr>
<th >Sl.no</th>
<th >Owner Name</th>
<th >Contact Number</th>
<th class="text-center" data-title="Action">Action</th>
</tr>
</thead>
<tbody id="responsive-table-body">
<?php
$owner=mysql_query("select id,tmp_id,name,phone,activate from pgowner where active='1'");
if(mysql_num_rows($owner)){
$i=0;
while($owner1=mysql_fetch_array($owner)){
$id=$owner1['tmp_id'];
?>
<tr>
<td><span class="label label-default"><?php echo ++$i; ?></span></td>
<td>
<a href='viewprofile?id=<?php echo $id; ?>' target='_blank' style='color:blue;text-decoration:underline;'><?php echo $owner1['name']; ?></a>
<input type="hidden" name="ownerid" value="<?php echo $owner1['tmp_id']; ?>" id="ownerid" />
</td>
<td>
<?php echo $owner1['phone']; ?>
</td>
<td>
<input type="checkbox" name="activate[]" class="activate" id="activate" />
</td>
</tr>
<?php } }
?>
</tbody>
</table>
Here's the ajax code to fetch the value from the row in which checkbox is checked.
<script type="text/javascript">
$(document).ready(function(){
$('#activate').click(function(){
var ownerid=$('#ownerid').val();
var myonoffswitch=$('#activate').val();
if ($("#activate:checked").length == 0)
{
var a='0';
}
else
{
var a="1";
}
$.ajax({
type: "POST",
url: "profileactivation",
data: "value="+a +"&ownerid="+ownerid,
success: function(html){
alert("Successfully Done");
}
});
});
});
</script>
I am not able to fetch the input value from the row in which checkbox is checked. Please help.
Generated HTML looks like this,
<table id="table" >
<thead>
<tr>
<th >Sl.no</th>
<th >Owner Name</th>
<th >Contact Number</th>
<th >Action</th>
</tr>
</thead>
<tbody id="responsive-table-body">
<tr >
<td ><span class="label label-default">1</span></td>
<td>
Name1
<input type="hidden" name="ownerid" value="EdXzrq" id="ownerid">
</td>
<td>
9731269342
</td>
<td>
<input type="checkbox" name="activate[]" class="activate" id="activate">
</td>
</tr>
<tr >
<td ><span class="label label-default">2</span></td>
<td>
Name2
<input type="hidden" name="ownerid" value="RowMpg" id="ownerid">
</td>
<td>
7760807087
</td>
<td>
<input type="checkbox" name="activate[]" class="activate" id="activate">
</td>
</tr>
</tbody>
</table>
There are multiple issues.
Since you have the controls in a loop, using ID will create multiple elements with same ID which is invalid, instead use class or other selectors like attribute selector to select elements.
<input type="checkbox" name="activate[]" class="activate" />
<input type="hidden" name="ownerid" value="<?php echo $owner1['tmp_id']; ?>" />
then use a class selector to register the click hanlder and then find the owner id in the same row as given below
$(document).ready(function() {
$('.activate').click(function() {
var ownerid = $(this).closest('tr').find('input[name="ownerid"]').val();
var a = this.checked ? 1 : 0;
$.ajax({
type: "POST",
url: "profileactivation",
data: {
value: a,
ownerid: ownerid
},
success: function(html) {
alert("Successfully Done");
}
});
});
});

Categories

Resources