Checkbox in a dynamic table with dynamic input fields - javascript

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");
}
});
});
});

Related

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

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>

Retrive data using PHP and Ajax

Here I am trying to fetch data from Mysql database using PHP and Ajax. My problem is, when I type the Test ID on test_id text box, just it immediatetly shows the Test Name according to the Test ID on test_name text box.
Here I used the function called checkname. In console just it show the Test Name but does not show in the test_name text box.
Here is the HTML code.
<table class="table table-hover table-white">
<thead>
<tr>
<th class="col-sm-1">Test ID</th>
<th class="col-md-6">Test Name</th>
<th style="width:100px;">Amount</th>
<th> Action</th>
</tr>
</thead>
<tbody id="rows">
<tr>
<td> <input class="form-control" type="text" style="width:200px" id="test_id[]" onblur="checkname();" onkeyup="checkname();" onchange="checkname();"> </td>
<td> <input type="text" style="width:300px" class="form-control text-right form-amt" readonly="" id="test_name[]" > </td>
<td> <input type="text" style="min-width:100px" class="form-control text-right form-amt" readonly="" id="amount[]"> </td>
<td><center> <i class="fa fa-plus"></i> </center> </td>
</tr>
</tbody>
</table>
Here is the Ajax code;
<script>
function checkname()
{
var test_id = document.getElementById("test_id[]").value;
$.ajax({
type: 'post',
url: "adminquery/fetch_test_name.php", // request file the 'check_email.php'
data: {'test_id': test_id, },
success: function (data) {
$("#test_name[]").html(data);
}
});
}
</script>
Here is the PHP code
<?php
include('../auth/dbconnection.php');
$output='';
$sql="SELECT * from testings where test_id='".$_POST['test_id']."'";
$result=mysqli_query($conn,$sql);
while($row=mysqli_fetch_array($result)){
$name= $row["testing_name"];
$output.=' <input type="text" readonly="" id="test_name[]" value="'.$name.' "> '.$name.' ';
}
echo $output;
?>
Anyone could help me may highly appreciated.
First lose the brackets in the id.
<input id="test_name" type="text" value="other" />
Then use .val() instead of .html()
$("#test_name").val("something")

Create an array of text fields using data from a database and use the values from the fields to do calculate

I would like to fetch items and item prices from database and use it to create an array of input fields for quantity and amount. Then use Jquery to automatically fetch the values of quantity as I type and multiply it by the price to display the amount in the amounts field for each item.
At the same time, the totals value (which is sum of all amounts) should also be displayed.
This is restricted to only the items that have been checked (selected).
<table class="form" id='tab1e'>
<tr>
<th> </th>
<th style="text-align: left;">Material Name</th>
<th style="text-align: center;">Quantity</th>
<th style="text-align: center;">Unit Price</th>
<th style="text-align: center;">Amount</th>
<th style="text-align: center;">Currency</th>
</tr>
<?php
foreach($database_result as $value){
?>
<tr>
<td>
<input type="checkbox" name="checkboxes[]" value="<?php echo $row['price']."".$row['item_name'] ?>">
</td>
<td style="width: 150px">
<?php echo $row['item_name'] ?>
</td>
<td>
<input name="qnty[]" id="qnty">
</td>
<td>
<input name="price" class="form-control" value="<?php echo $row['price']) ?>" id="price">
</td>
<td>
<input name="total_amount[]" class="text form-control" readonly="readonly" id="total_amount">
</td>
</tr>
<?php } ?>
<tr>
<td>Total Amount</td>
<td style="text-align: right;" id="totalpop"></td>
<td></td>
</tr>
</table>
First thing is the inputs should have different ids.
Now, you can use onchange event to call a function when input value changes. You can use plain javascript for that. Here's an example:
<html>
<body>
<script>
function o(id) {
return document.getElementById(id);
}
function updatePrice(id) {
if (!o('qnty'+id).value.match(/^[0-9]+$/)) {
alert('Invalid quantity');
o('total'+id).value = '0';
return false;
}
// Similar check for price
o('total'+id).value = parseInt(o('qnty'+id).value) * parseFloat(o('price'+id).value);
}
</script>
<input name="qnty[]" onchange="updatePrice('1')" id="qnty1">
<input name="price" value="1" onchange="updatePrice('1')" id="price1">
<input name="total_amount[]" id="total1">
</body>
</html>
The 1 corresponds to row number, so you would need to change your PHP code so it has a row number (can be just a simple $i=1; before the loop and $i++; in the end of every loop iteration).

how to hide datatable rows where code is have "." e.g 1.1, 1.2 through jquery?

I take data of two inputs to another page through ajax. I used these two values in the query and shown the result of the select query in a data table which is return back to success function and shown in the table on the main page.
After that, I want to use a condition that data with "." (accounting->subaccounts) hide unless He clicks a button.
I just need an idea to hide it I can do more. let me show you my code.
This is the button:
<input type="button" id="generate" onclick="getData();" value="Generate"
class="btn btn-block btn-primary btn-sm" />
The div where i shown the table:
<div class="col-lg-12 col-sm-12 col-xs-12 col-md-12" id="tab"></div>
the ajax function:
function getData() {
var date = $("#date").val();
var classId = $("#class").val();
$.ajax({
url: "ajax/getTrailBalanceData.php",
type: "POST",
data: {
"date": date,
"classId": classId,
},
cache: false,
async: false,
success: function (data) {
//alert(data);
$("#tab").html(data);
var row_main_code = $("#main_code").val();
if (row_main_code.indexOf(".") > -1) {
// $("#tbl_row").addClass("hide");
} else {
// $("#tbl_row").removeClass("hide");
// $("#main_code").parents("tr").hide();
// $("#tbl_row").addClass("hide");
// $("#main_code").val("hide");
}
}
});
}
The if(rowmaincode.indexof('.')>-1) condition in "success" I tried but not give desirable result I am confused I don't know why but let me show you the other page code:
<table id="trail_balance_list" class="table table-bordered table-condensed bootstrap-datatable datatable responsive">
<thead id="table_head">
<tr class="bg-success">
<th class=" text-center">Code</th>
<th class=" text-center">Account Title</th>
<th class=" text-center" >Debit</th>
<th class=" text-center" >Credit</th>
<th class=" text-center" >Action</th>
</tr>
</thead>
<tbody>
<?php
while ($row = mysqli_fetch_assoc($result)) {
?>
<tr id="tbl_row" class="">
<td><?php echo $row['main_code']; ?><input type="hidden" id="main_code" value="<?php echo $row['main_code']; ?>" /></td>
<td><?php echo $row['account_title']; ?></td>
<td></td>
<td></td>
<td class="text-center"><button class="btn btn-info"><i class="fa fa-arrow-down"></i></button></td>
</tr>
<?php
}
?>
</tbody>
<tfoot>
<tr>
<th><input type="hidden" id="total_credit_input" name="total_credit" value="0" /></th>
<th><input type="hidden" id="total_debit_input" name="total_debit" value="0" /></th>
<td class="bg-warning text-center" id="total_debit">0.00</td>
<td class="bg-warning text-center" id="total_credit" >0.00</td>
</tr>
</tfoot>
</table>
<script>
$(document).ready(function () {
$("#trail_balance_list").dataTable();
});
</script>
the result I get is like : (see image), I want to show only like 1,2,3,4
You have implement a similar idea in your code, hope you can do that. I have added a sample below.
$('body').on('click', '#act_button', function() {
$('#trail_balance_list > tbody > tr').each(function() {
if ($(this).find('td:first').text().indexOf('.') >= 0) {
$(this).hide();
} else {
$(this).show();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="act_button">hide decimal rows</button>
<table id="trail_balance_list" border="1">
<tbody>
<tr>
<td>1</td>
<td>222</td>
</tr>
<tr>
<td>33.3</td>
<td>444</td>
</tr>
<tr>
<td>555</td>
<td>666</td>
</tr>
<tr>
<td>77</td>
<td>666</td>
</tr>
</tbody>
</table>

How to update values of checkbox to the database 1 if checked and 0 if unchecked?

This is my database
<?php
if(isset($_POST["insert"]))
{
$conn = mysqli_connect("localhost", "root", "", "databaseappfeature");
if(isset($_POST["insert"]) == "1"){
$query = "UPDATE appfeature SET feature_switch = ('".$_POST["insert"]."')";
$result = mysqli_query($conn, $query);
echo "Data Inserted Successfully!";
}
}
?>
This is my javascript code
<script>
$(document).ready(function(){
$('#submit').click(function(){
var insert = [];
$('.get_value').each(function(){
if($(this).is(":checked"))
{
insert.push($(this).val());
}
});
insert = insert.toString();
$.ajax({
url: "insert.php",
method: "POST",
data:{insert:insert},
success:function(data){
$('#result').html(data);
}
});
});
});
</script>
This is my checkbox code
<form action="" method="POST">
<h4 id="result"></h4>
<div class="container">
<h2 align="center">Table App Feature</h2>
<table id="appFeature" class="table table-hover" align="center" style="width:500px;margin:auto;">
<thead>
<tr>
<th>Firstname</th>
<th>Please check to enable the features</th>
</tr>
</thead>
<tbody>
<tr>
<td>Smarthome</td>
<td>
<input type="checkbox" class="get_value" value="1" />
</td>
</tr>
<tr>
<td>Intercom</td>
<td>
<input type="checkbox" class="get_value" value="1" />
</td>
</tr>
<tr>
<td>Visitors</td>
<td>
<input type="checkbox" class="get_value" value="1" />
</td>
</tr>
<tr>
<td>Booking</td>
<td>
<input type="checkbox" class="get_value" value="1" />
</td>
</tr>
<tr>
<td>Access</td>
<td>
<input type="checkbox" class="get_value" value="1" />
</td>
</tr>
<tr>
<td>Parcel</td>
<td>
<input type="checkbox" class="get_value" value="1" />
</td>
</tr>
<tr>
<td>Bills</td>
<td>
<input type="checkbox" class="get_value" value="1" />
</td>
</tr>
<tr>
<td>Invoices</td>
<td>
<input type="checkbox" class="get_value" value="1" />
</td>
<tr>
<td>Receipts</td>
<td>
<input type="checkbox" class="get_value" value="1" />
</td>
</tr>
<tr>
<td>Transactions</td>
<td>
<input type="checkbox" class="get_value" value="1" />
</td>
</tr>
<tr>
<td>Meeting</td>
<td>
<input type="checkbox" class="get_value" value="1" />
</td>
</tr>
<tr>
<td>Vote</td>
<td>
<input type="checkbox" class="get_value" value="1"/>
</td>
</tr>
<tr>
<td>Feedback</td>
<td>
<input type="checkbox" class="get_value" value="1" />
</td>
</tr>
</tbody>
</table><br />
<div align="center">
<button type="button" name="submit" id="submit">Update</button>
</div>
</div>
</form>
How can i update the value of multiple checkbox into the database and the value should be 1 if the checkbox is checked and 0 if the checkbox is unchecked??
This is my checkboxThis is jquery that i use to pass the value of checkboxThis is my database code
Please help me..i'm very new to this..and i'm doing this for a week..
Please go though documentation and understand the way how the forms works. There are plenty of examples out there I would recommend Head First book series and here you can find a good example.
And also here is the example code for your problem
create a file named example.html and save this content
<html>
<head>
<!-- link to jquery lib -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<form action="" method="POST">
<h4 id="result"></h4>
<div class="container">
<h2 align="center">Table App Feature</h2>
<label> Name </label>
<input type='text' name='name' id='name' value=''/>
<table id="appFeature" class="table table-hover" align="center" style="width:500px;margin:auto;">
<thead>
<tr>
<th>Firstname</th>
<th>Please check to enable the features</th>
</tr>
</thead>
<tbody>
<tr>
<td>Smarthome</td>
<td>
<!-- checkbox for smarthome value -->
<input type="checkbox" class="get_value" id='smarthome'/>
</td>
</tr>
<tr>
<td>Intercom</td>
<td>
<input type="checkbox" class="get_value" id='intercom'/>
</td>
</tr>
</tbody>
</table><br />
<div align="center">
<label>check if you want to update, unckeck if you want to insert</label>
<input type="checkbox" class="get_value" id='update'/>
<br>
<!-- button name -->
<button type="button" name="submit" id="submit">Update or Insert</button>
</div>
</div>
</form>
</body>
<script type="text/javascript">
$(document).ready(function(){
$('#submit').click(function(){
// get the value is checked from the form
$.ajax({
url: "insert.php",
method: "POST",
data:{intercom: $('#intercom').is(':checked'),smarthome: $('#smarthome').is(':checked'), name: $('#name').val(), update: $('#update').is(':checked')},
success:function(data){
$('#result').html(data);
}
});
});
});
</script>
</html>
php file as follows named insert.php . make sure both files are in the same directory and inside your apache server.(localhost public directory)
<?php
$servername = "localhost";
$username = "YOURDBUSER";
$password = "YOURDBPASSWORD";
$dbname = "databaseappfeature"; // db name
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql ;
if($_POST['update']){
$sql = "UPDATE appfeature SET smarthome=".$_POST['smarthome'].", intercom=".$_POST['intercom']." WHERE name='".$_POST['name']."'";
}else{
$sql = "INSERT INTO appfeature (name, smarthome, intercom) VALUES ('".$_POST['name']."',".$_POST['smarthome'].",".$_POST['intercom'].")";
}
if ($conn->query($sql) === TRUE && !$_POST['update']) {
echo "New record created successfully";
}else if($conn->query($sql) === TRUE && $_POST['update']){
echo "record updated";
}else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
here is the sql file related to the database i used

Categories

Resources