jquery not working after dynamic add table row - javascript

I have the following codes which makes an select list to auto populate from a table and another which auto populate from another table (both in the same db) without using a submit button. All works ok but there is also a button that if clicked will make another table row with the same select fields.
The questions are: - what is wrong in the code because when i click on add another row button, it displays another row but only the first select is operational. i need both select to be operational; - what to use instead of the first javascript code for the cloning of the row but keep full functionality
Here are the codes:
Javascript for new row
<script>
function addField(n) {
var tr = n.parentNode.parentNode.cloneNode(true);
document.getElementById('tbl').appendChild(tr);
}
</script>
script querying
<script>
$(document).ready(function() {
$("#id_produs").change(function() {
var id_produs = $(this).val();
$.ajax({
url: 'query.php',
type: 'post',
data: {
id_produs: id_produs
},
dataType: 'json',
success: function(response) {
var len = response.length;
$("#cod_produs").empty();
for (var i = 0; i < len; i++) {
var id_produs = response[i]['id_produs'];
var cod_produs = response[i]['cod_produs'];
$("#cod_produs").append("<option value='" + id_produs + "'>" + cod_produs + "</option>");
}
}
});
});
});
</script>
PHP & HTML
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table id="tbl">
<tr>
<td>Produse</td>
<td>Cod Produs</td>
<td>Cantitate</td>
<td></td>
</tr>
<tr>
<td>
<select id="id_produs">
<option value="0">- Select -</option>
<?php
if ($rezultatproduse->num_rows > 0) {
while($rowproduse = $rezultatproduse->fetch_assoc()) {
?>
<option value="<?php echo $rowproduse[" id_denumire "]; ?>">
<?php echo $rowproduse["denumire"]; ?>
</option>
<?php
}
}
?>
</select>
</td>
<td>
<select id="cod_produs">
<option value="0">- Select -</option>
</select>
</td>
<td>
<input type="text" name="cantitate" />
</td>
<td><input type="submit" class="button" value="Add another line" onclick="addField(this);" /></td>
</tr>
</table>
and also query.php
<?php
include "conn.php";
$id_produs = $_POST['id_produs'];
$sql = "SELECT id_produs, cod_produs FROM coduri_produse WHERE id_produs = ".$id_produs;
$result = mysqli_query($conn,$sql);
$coduri_arr = array();
while( $row = mysqli_fetch_array($result) ){
$id_produs = $row['id_produs'];
$cod_produs = $row['cod_produs'];
$coduri_arr[] = array("id_produs" => $id_produs, "cod_produs" => $cod_produs);
}
// encoding array to json format
echo json_encode($coduri_arr);
?>

Change this
$("#id_produs").change(function() {
to this
$(document).on('change', "#id_produs", function() {
If you want an event to work on dynamically added elements you need to bind it to document and not to elements. Because jQuery bunds an event only to elements which are currently in DOM.
$(document).on('change', "#id_produs", function() {
var id_produs = $(this).val();
$.ajax({
url: 'query.php',
type: 'post',
data: {
id_produs: id_produs
},
dataType: 'json',
success: function(response) {
var len = response.length;
$("#cod_produs").empty();
for (var i = 0; i < len; i++) {
var id_produs = response[i]['id_produs'];
var cod_produs = response[i]['cod_produs'];
$("#cod_produs").append("<option value='" + id_produs + "'>" + cod_produs + "</option>");
}
}
});
});
function addField(n) {
var tr = n.parentNode.parentNode.cloneNode(true);
document.getElementById('tbl').appendChild(tr);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table id="tbl">
<tr>
<td>Produse</td>
<td>Cod Produs</td>
<td>Cantitate</td>
<td></td>
</tr>
<tr>
<td>
<select id="id_produs">
<option value="0">- Select -</option>
<option value="test_value">
test value
</option>
</select>
</td>
<td>
<select id="cod_produs">
<option value="0">- Select -</option>
</select>
</td>
<td>
<input type="text" name="cantitate" />
</td>
<td><input type="submit" class="button" value="Add another line" onclick="addField(this);" /></td>
</tr>
</table>
EDIT
Also you should avoid adding elements with the same id.
That is the reason why wrong select is activated. Change id to class and of course in jQuery change id to class.
The same goes for this $("#cod_produs"). Make sure that you get the exzact element. Because right now it will work for all elements with id="cod_produs".
So change to something like this (example):
Instead of this
$("#cod_produs").empty();
do
$(this).closest(".cod_produs").empty();

Related

SelectPicker adding options dynamically depend input value

Morning,
I'm trying to create a table with dropdown (selectpicker A) fill dynamically with data selected with result of other input (selectpicker B) not into this table.
Filling (SelectPicker A) its OK for first row of table after selected value into SelectPicker B.
But when i add new line (by clone), SelectPicker A is empty for second row.
Need your help, thks !
My view code :
<select class="form-control selectpicker" name="nc_A" id="nc_A" onchange="select_B(this)" type="string" required>
<option disabled> </option>
</select>
...
<table id="sub_table" class="table">
<thead">
<tr>
<th>{{__('test.B')}}</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<select class="form-control" name="nc_B[]" id="nc_B" type="string" required>
<option> </option>
</select>
</td>
</tr>
</tbody>
</table>
<i class="btn" onclick="add_row()">{{" + ".__('home.ajoutligne')}}</i>
My Jquery code :
var clonednc = $("#sub_table tbody tr:first").clone()
$("select[name*=nc_B]").selectpicker()
function add_row() {
$(clonednc).find("input").val("")
$("<tr>" + $(clonednc).html() + "</tr>").appendTo($("#sub_table tbody"))
$("#sub_table tbody tr:last select").selectpicker()
}
function select_B(e)
{
var selectionA = e.value;
$.ajax({
type: "POST",
url: "/production/selectionB",
data: {_token: CSRF_TOKEN, ncA : selectionA },
dataType: "JSON",
success: function (data) {
$(e).parents('div').find('#nc_B').empty();
$.each(data, function(key,value){
$(e).parents('div').find('#nc_B').append('<option value="'+value.NumB+'">'+ value.NumB +'</option>');
});
$("select[name*=nc_B]").selectpicker('refresh');
}
});
}

How to auto change select in accordance with same row table using jQuery ajax change function

I have form input dynamically row on table area. My first schema on first row is running well using automatic filling field change ajax function:
but I have problem in the second row and next row too. When I change the select option on second row, the previous field changed (not same row as what I have changed):
How to automatic filling same row with the select option..?
Here my html code:
<?php echo form_open_multipart(base_url().'back/transaksi/Order/insert_temp', array('role' => 'form', 'class' => 'form-horizontal', 'method'=>'POST','id'=>'Validation_form'));?>
<fieldset style="min-width: 0;padding:.35em .625em .75em!important;margin:0 2px;border: 2px solid black!important;margin-bottom: 10em;">
<legend style="border-bottom: none;width: inherit !important; padding:inherit; font-weight:bold; color:red;">Form Input</legend>
<button class="btn btn-success add_field_button" type="button" onClick="addRow('dataTable')">Add </button>
<input type="button" class="btn btn-danger" value="Remove" Field" onClick="deleteRow('dataTable')"/>
<div> </div>
<table id="dataTable" class="table table-striped table-responsive table-bordered dataTable" width="100%">
<thead>
<tr>
<th><input type="checkbox" id="selectall" value="selectAll"/></th>
<th class="text-center">No</th>
<th class="text-center">Item</th>
<th class="text-center">Konversi</th>
<th class="text-center">Spesifikasi</th>
<th class="text-center">qty</th>
<th class="text-center">Satuan</th>
<th class="text-center">Note</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="checkbox" class="check"></td>
<td id="no">
</td>
<td>
<select name="id_komoditi[]" id="id_komoditi" class="form-control chzn_select_L">
<option value="">--- Pilih Item ---</option>
<?php
foreach($id_komoditi as $a)
{
echo "<option value='".$a['id_komoditi']."'>".$a['nama_komoditi']."</option>";
}
?>
</select>
</td>
<div class="input_fields_wrap1">
<div><input type="hidden" name="id_order[]" id="id_order" value="<?php echo $_GET['id'];?>"></div>
</div>
<div class="input_fields_wrap">
<div><input type="hidden" name="item[]"></div>
</div>
<td>
<select name="id_konversi_satuan[]" id="id_konversi_satuan" class="form-control chzn_select_R">
<option value="">--- Pilih Konversi ---</option>
<?php
foreach($id_konversi_satuan as $a)
{
echo "<option value='".$a['id_konversi_satuan']."'>".$a['satuan_awal']."</option>";
}
?>
</select>
</td>
<td><input name="spesifikasi[]" id="spesifikasi" type="text" class="form-control"></td>
<td><input name="qty[]" id="qty" type="text" class="form-control"></td>
<td><input name="satuan[]" id="satuan" type="text" class="form-control"></td>
<td><textarea name="note[]" id="note" type="text" class="form-control"></textarea></td>
</tr>
</tbody>
</table>
<button style="border-radius: 3px; box-shadow: 0 3px 6px rgba(0,0,0,0.9);" type="submit" class="btn btn-success">Entry</button>
</fieldset>
</form>
Here is my jQuery/Javascript code // for first change schema
$(document).ready(function(){
dataTable();
$('#selectall').click(function(event)
{
if(this.checked)
{
$('.check').each(function()
{
this.checked = true;
});
}
else
{
$('.check').each(function() {
this.checked = false;
});
}
});
$('#id_komoditi').on('change',function(){
$.ajax({
url: '<?=base_url();?>back/transaksi/Order/Detail_Item',
method: 'POST',
data:{
id_komoditi: $('#id_komoditi').val(),
},
dataType:'json',
success:function(hasil)
{
$('#spesifikasi').val(hasil.spesifikasi);
}
});
});
});
and here the dynamically add row input Javascript function:
function addRow(dataTable){
var table = document.getElementById(dataTable);
var rowCount = table.rows.length;
if(rowCount < 301)
{
$(".chzn_select_L").chosen('destroy');
$(".chzn_select_R").chosen('destroy');
var row = table.insertRow(rowCount);
var colCount = table.rows[1].cells.length;
var wrapper = $(".input_fields_wrap");
var wrapper1 = $(".input_fields_wrap1");
$(wrapper).append('<div><input type="hidden" name="item[]"/></div>');
$(wrapper1).append('<div><input type="hidden" name="id_order[]" value="<?php echo $_GET['id'];?>"/></div>');
for(var i=0; i<colCount; i++)
{
var newcell = row.insertCell(i);
newcell.innerHTML = table.rows[1].cells[i].innerHTML;
}
}
else
{
alert("Maximum is 300.");
}
$(".chzn_select_L").chosen().on('change',function(e){
event.stopImmediatePropagation();
var id_komoditi = $(this).val();
$.ajax({
url: '<?=base_url();?>back/transaksi/Order/Detail_Item',
method: 'POST',
data:{
id_komoditi: id_komoditi,
},
dataType:'json',
success:function(hasil)
{
$('#spesifikasi').val(hasil.spesifikasi);
}
});
});
$(".chzn_select_R").chosen();}
The Problem is, you didn't specify any row number here
success:function(hasil)
{
$('#spesifikasi').val(hasil.spesifikasi);
}
that's why it's only changed the first element, since it didn't know which "spesifikasi" input to be changed.
SOLUTION
you should have something like this
<select name="id_komoditi[]" id="id_komoditi" class="form-control chzn_select_L" data-spesifikasi="0">
and this on your first spesifikasi input
with the value of data-spesifikasi is the same as the row number to change.
then edit your addRow function at the iteration line, so it will give row number value for the necessary input column
for(var i=0; i<colCount; i++)
{
var newcell = row.insertCell(i);
newcell.innerHTML = table.rows[1].cells[i].innerHTML;
cellToChange = $(newcell).find('.form-control');
if($(cellToChange[0]).attr("class") == "form-control chzn_select_L")
$(cellToChange[0]).data("spesifikasi", (rowCount-1))
else if($(cellToChange[0]).attr("id") == "spesifikasi0")
$(cellToChange[0]).attr("id", "spesifikasi"+(rowCount-1))
}
and your chosen() function to be like this :
$(".chzn_select_L").chosen().on('change',function(e){
event.stopImmediatePropagation();
var id_komoditi = $(this).val();
var spesifikasi_target = $(this).data("spesifikasi");
$.ajax({
url: '<?=base_url();?>back/transaksi/Order/Detail_Item',
method: 'POST',
data:{
id_komoditi: id_komoditi,
},
dataType:'json',
success:function(hasil)
{
$('#spesifikasi'+spesifikasi_target).val(hasil.spesifikasi);
}
});
});
The number/index 0 is responsible for each row number you use, hence
you should change each input you're using to have an index in their id
and name to be the same as their row number
Therefore, you will get different target spesifikasi for each select input
P.S : Just ask more if you're still unclear about them
Your first change:
$('#id_komoditi').on('change',function(){
//...
success:function(hasil)
{
$('#spesifikasi').val(hasil.spesifikasi);
}
});
Your second change:
$(".chzn_select_L").chosen().on('change',function(e){
//...
success:function(hasil)
{
$('#spesifikasi').val(hasil.spesifikasi);
}
});
Both times you are changing #spesifikasi, so either you have the id multiple times which you need to change, or you have a different id then you need to use that one in the second function.

How to insert the multiple row values of a table into the database using php

<html>
<body>
<form method="POST" action="">
<label>Select your Category:</label>
<input type="text" name="category" id="cat-list"/>
</br>
<label> Display Name:</label>
<input type="text" name="display_name" id="displayname"/>
</br>
<label> Select your Subcategory:</label>
<input type="text" name="pagename" id="subcat-list"/>
</br>
<label>Set Order</label>
<select name="privilage" id="privilage" required>
<option value="">Select</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
</br>
<button type="button" name="add" id="savebutton"><i class="icon-check-sign" aria-hidden="false"></i>Add</button>
<table id="pTable" class="table table-hover" width="100%" cellspacing="0" style="border: 1px; height:10px;" >
<thead style="background-color:#CCE5FF">
<tr id="row">
<th>Category</th>
<th>DisplayName</th>
<th>Subcategory</th>
<th>Order</th>
<th colspan=2>Action</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<button type="submit" name="import" > Import Database</button>
</form>
<script src=" https://code.jquery.com/jquery-3.2.1.js" type="text/javascript"></script>
<script>
var i=0;
currentRow = null;
$("button#savebutton").click(function(){
var cat = $("#cat-list").val();
var display = $("#displayname").val();
var subcat = $("#subcat-list").val();
var order = $("#privilage").val();
i++;
//Inserting first row to the table with edit and delete button
var new_row = "<tr id='row"+i+"' class='info'><td class='cat'>" + cat + "</td><td class='display'>" + display + "</td><td class='type'>" + subcat +"</td><td>"+order +"</td><td><span class='editrow'><a class='fa fa-edit' href='javascript: void(0);'>Edit</a></span></td><td><span class='deleterow'><a class='glyphicon glyphicon-trash' href=''>Delete</a></span></tr>";
//Appending the new row to the table
if(currentRow){
$("table tbody").find($(currentRow)).replaceWith(new_row);
currentRow = null;
}
else{
$("table tbody").append(new_row);
}
});
//Editing the row entered
$(document).on('click', 'span.deleterow', function () {
$(this).parents('tr').remove();
return false;
});
//Deleting the row
$(document).on('click', 'span.editrow', function () {
currentRow= $(this).parents('tr');
});
</script>
<?php
require('connection1.php');
echo 123;
if(isset($_POST['import'])){
$query=mysqli_query($db,"INSERT INTO selectedpages(display_name,category,pagename,privilage) values('".$_POST['display_name']."','".$_POST['category']."','".$_POST['pagename']."','".$_POST['privilage']."')") or die(mysqli_error($db));
if($query>0){
echo "Success";
}
else {
echo "failed";
}
}
?>
Content:
The code is to enter the multiple row values to the database,but the problem is only the last row value is entering into database.If there are 3 rows ,only the third row details entering into the database.Firstly, the form having a add button and an import button.Add button is used for adding the rows and then have to click the import button for entering these row values to the database.
When you submit your form it sends the inputs via post, not the whole table. And since in the inputs are still the values of the last added row, it sends these values via POST, which are getting inserted into the db.
Here is how you could solve it:
1) intercept the formsubmit with a javascript onclick method (where you will have to use e.preventDefault to stop the actual submit).
2) read all table rows with jQuery, create an array selectedPages with them that looks something like this:
(this is how it should look after, its not how you create it :P)
selectedPages {
[
"category": "Foo",
"displayName": "FooBar",
"pageName": "Bar",
"privilage": 1
],[
"category": "Foo",
"displayName": "FooBar",
"pageName": "Bar",
"privilage": 1
],[
"category": "Foo",
"displayName": "FooBar",
"pageName": "Bar",
"privilage": 1
]
}
3) create new php file where you put your php code that you currently have in the bottom of the same file.
4) make an AJAX post request to the new php file send your selectedPages as data
5) in the php file, iterate over the array and insert each item in your DB.
You must prevent the form submission. And create a JSON
data string by reading the table #pTable.
Add a hidden field <input type="hidden" name="import_data"> inside your form. It passes the JSON string to the server side.
I have made some changes in you HTML:
var i = 0;
currentRow = null;
$("button#savebutton").click(function() {
var cat = $("#cat-list").val();
var display = $("#displayname").val();
var subcat = $("#subcat-list").val();
var order = $("#privilage").val();
i++;
//Inserting first row to the table with edit and delete button
var new_row = "<tr id='row" + i + "' class='info'><td class='cat'>" + cat + "</td><td class='display'>" + display + "</td><td class='type'>" + subcat + "</td><td>" + order + "</td><td><span class='editrow'><a class='fa fa-edit' href='javascript: void(0);'>Edit</a></span></td><td><span class='deleterow'><a class='glyphicon glyphicon-trash' href=''>Delete</a></span></tr>";
//Appending the new row to the table
if (currentRow) {
$("table tbody").find($(currentRow)).replaceWith(new_row);
currentRow = null;
} else {
$("table tbody").append(new_row);
}
});
//Editing the row entered
$(document).on('click', 'span.deleterow', function() {
$(this).parents('tr').remove();
return false;
});
//Deleting the row
$(document).on('click', 'span.editrow', function() {
currentRow = $(this).parents('tr');
});
$('#import-form').submit(function(event) {
var import_data = $('[name=import_data]');
if (import_data.val() == "") {
event.preventDefault();
var tbl = $('table#pTable tr').get().map(function(row) {
return $(row).find('td').get().map(function(cell) {
return $(cell).html();
});
});
var convertTableToJson = function() {
var rows = [];
$('table#pTable tr').each(function(i, n) {
// Ignore empty
if (i != 0) {
var $row = $(n);
rows.push({
display_name: $row.find('td:eq(0)').text(),
category: $row.find('td:eq(1)').text(),
pagename: $row.find('td:eq(2)').text(),
privilage: $row.find('td:eq(3)').text()
});
}
});
return JSON.stringify(rows);
};
import_data.val(convertTableToJson);
$(this).submit();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<body>
<form method="POST" action="" id="import-form">
<label>Select your Category:</label>
<input type="text" name="category" id="cat-list" />
</br>
<label> Display Name:</label>
<input type="text" name="display_name" id="displayname" />
</br>
<label> Select your Subcategory:</label>
<input type="text" name="pagename" id="subcat-list" />
</br>
<label>Set Order</label>
<select name="privilage" id="privilage" required>
<option value="">Select</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
</br>
<button type="button" name="add" id="savebutton"><i class="icon-check-sign" aria-hidden="false"></i>Add</button>
<table id="pTable" class="table table-hover" width="100%" cellspacing="0" style="border: 1px; height:10px;">
<thead style="background-color:#CCE5FF">
<tr id="row">
<th>Category</th>
<th>DisplayName</th>
<th>Subcategory</th>
<th>Order</th>
<th colspan=2>Action</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<button type="submit" name="import"> Import Database</button>
<input type="hidden" name="import_data">
</form>
</body>
</html>
and also replace your PHP block,
<?php
require('connection1.php');
echo 123;
if(isset($_POST['import'])){
$query=mysqli_query($db,"INSERT INTO selectedpages(display_name,category,pagename,privilage) values('".$_POST['display_name']."','".$_POST['category']."','".$_POST['pagename']."','".$_POST['privilage']."')") or die(mysqli_error($db));
if($query>0){
echo "Success";
}
else {
echo "failed";
}
}
?>
with below
<?php
require('connection1.php');
if (isset($_POST['import_data'])) {
$import_data = json_decode($_POST['import_data'], true);
$query = "INSERT INTO selectedpages (display_name,category,pagename,privilage) VALUES ";
$values = array();
// Create value rows array
foreach ($import_data as $key => $row) {
// Added single quotes
$values[] = "('" . implode("', '", $row) . "')";
}
$query .= implode(", ", $values);
echo $query;
$execute_query = mysqli_query($db, $query) or die(mysqli_error($db));
if($execute_query>0)
{
echo "Success";
}
}
?>
Every input that u are adding in the #pTable table should be array, for example, product[], then in your PHP code you traverse the array in a for/foreach and insert each row in DB

change only works for the first row in a table

I am selecting an item from a select-option tag in a table to populate records from a database to fill another input field, but unfortunately, it only works for the first table row. When I add another table row with jquery, it does not work in the new added table row.
<table class="table table-borderd table-hover">
<thead>
<tr>
<th>Product Name</th>
<th>Price</th>
<th>Quantity</th>
<th>Discount %</th>
<th>Total</th>
<th><input type="button" class="btn btn-primary addmore" value="+"></th>
</tr>
</thead>
<tbody id="itemlist2" class="detailss">
<tr>
<td>
<select class="select-product form-control" name="product_name[]">
<option value="">
</option>
<?php
foreach ($product as $key ):
?>
<option value="<?php echo $key['id'] ?>">
<?php echo $key['product_name'] ?>
</option>
<?php endforeach; ?>
</select>
</td>
<td>
<input type="text" name="price[]" class="price form-control" value="">
</td>
<td><input type="text" name="quantity[]" class="form-control"></td>
<td><input type="text" name="discount[]" class="form-control"></td>
<td><input type="text" name="total[]" class="form-control"></td>
</tr>
</tbody>
</table>
The script that add new row to table
<script>
var i=$('#itemlist2 tr').length;
$(".addmore").on('click',function(){
html = '<tr>';
html += '<td><select class="select-product form-control" name="product_name[]"> <option value=""> </option><?php foreach ($product as $key ): ?><option value="<?php echo $key['id'] ?>"><?php echo $key['product_name'] ?></option><?php endforeach; ?></select></td>';
html += '<td><input type="text" name="price[]" class="price form-control" value=""></td>';
html += ' <td><input type="text" name="quantity[]" class="form-control"></td>';
html += '<td><input type="text" name="discount[]" class="form-control"></td>';
html += '<td><input type="text" name="total[]" class="form-control"></td>';
html += '</tr>';
$('#itemlist2').append(html);
i++;
});
</script>
The onchange function with ajax
<script>
$(function() {
$(document).on('change', '.select-product', function(){
$(this).change(function(){
var id=$(this).val();
var dataString = 'id='+ id;
$.ajax({
type: "GET",
url: "<?php echo site_url('/product/view_data'); ?>",
data: dataString,
cache: false,
success: function(html){
$('.price').parent().parent().find('.price').val(html);
}
});
});
});
});
</script>
Thanks for your time!
Use delegate for dynamically added element. For example
$(document).delegate( ".select-product", "change", function() {
$(this).change(function(){
var id=$(this).val();
var dataString = 'id='+ id;
$.ajax({
type: "GET",
url: "<?php echo site_url('/product/view_data'); ?>",
data: dataString,
cache: false,
success: function(html){
alert(html);
// $("#price").val(html);
}
});
});
});
});
I hope it will help you.
New added elements does not have the event binding.
The quickest fix is just change your event binding code from
$('input').change(function () {
// Do some stuff.
});
to
$(document).on('change', 'input', function() {
// Do some stuff.
});
Check these following lines:
html += '<td><select class="select-product form-control" id="product" ....
and
var id=$("#product").val();
You are assigning an id to multiple rows and trying to get the values using id which is unique. That's why you are getting the data for first row only.
To solve this, refer it using class and $(this) to get the value of current instance.

how to use the same ajax function for multiple buttons

i want call the same ajax function for multiple buttons please help me the code is given below. this code will generate buttons and when we click on the buttons it prints the details ...please solve. This code will generate buttons in table.
<head>
<script>
$(document).ready(function()
{
$("#save").click(function()
{
var sel = $("#response").val();
var fudate=$("#fdate").val();
var cmd=$("#cm").val();
var id=$("#id").val();
$.ajax(
{
type: "POST",
url: "autosave.php",
data: {response:sel,fdate:fudate,cm:cmd,id:id},
success: function(result)
{
alert('result');
$a= $("#ak").html(result);
}
});
});
});
</script>
</head>
<body>
<div id="company_details">
<div id="ak"></div>
<table border="1" align="left">
<tr>
<th >Company</th>
<th>Contact Person</th>
<th>Contact Person's No.</th>
<th>HR</th>
<th>HR's No.</th>
<th>Current Vacancies</th>
<th>Response</th>
<th>Follow Up Date</th>
<th>Comment</th>
<th></th>
<th>Edit</th>
</tr>
<?php
$con=mysql_connect("localhost","root") or die("Error In Connection:-".mysql_error());
mysql_select_db("ttcs",$con) or die("Error In DB Selection:-".mysql_error());
$sql="select * from company_details";
$rs=mysql_query($sql) or die(mysql_error());
while($row=mysql_fetch_array($rs))
{
?>
<tr>
<td>
<input type="text" name="name" value= <?php $e=$row[0];echo $row[1];?>></td>
<td><input type="text" name="cp" value= <?php echo $row[7]; ?>></td>
<td><input type="text" name="cpn" value= <?php echo $row[9]; ?>></td>
<td><input type="text" name="hr" value= <?php echo $row[10]; ?>></td>
<td><input type="text" name="hrn" value= <?php echo $row[12]; ?>></td>
<td>
<?php
$sql2="select * from vacancies where company_id='$e'";
$rs2=mysql_query($sql2);
if($rs2)
{
while($row2=mysql_fetch_array($rs2))
{?>
<textarea name="cv" value=<?php echo $row2[1];?>></textarea>
<?php }}?>
</td>
<td>
<select name="response" id="response">
<option value="Not interested">Not Interested</option>
<option value="Not responding">Not Responding</option>
<option value="follow up">Follow up</option>
<option value="Interested">Interested</option>
</select></td>
<?php
$sql1="select * from call_details_company where company_id=$row[0]";
$rs1=mysql_query($sql1);
$row1=mysql_fetch_array($rs1);
?>
<input type="date" name="fdate" id="fdate" value=<?php echo $row1[3];?>>
<input type="text" name="cm" id="cm" value=<?php echo $row1[5];?>>
<button id="save" >save</button>
</td>
</tr>
<?php
}
?>
</body>
ID of an element must be unique, so within the loop don't use ID, change the id of the button to class value then use the input element's name to find the relative elements within the tr
$(document).ready(function () {
$(".save").click(function () {
var $tr = $(this).closest('tr')
var sel = $tr.find("select").val();
var fudate = $tr.find('input[name="fdate"]').val();
var cmd = $tr.find('input[name="cm"]').val();
//need to fix this selector #id too, not able to locate it in the given html structure
var id = $tr.find("#id").val();
$.ajax({
type: "POST",
url: "autosave.php",
data: {
response: sel,
fdate: fudate,
cm: cmd,
id: id
},
success: function (result) {
alert('result');
$a = $("#ak").html(result);
}
});
});
});
use like this
<script>
function ajaxCallDemo() {
var sel = $("#response").val();
var $tr = $(this).closest('tr');
var cmd = $tr.find("input[name='cm']").val();
var fudate = $tr.find("input[name='fdate']").val();
var id = $tr.find("#id").val();
$.ajax({
type: "POST",
url: "autosave.php",
data: {
response: sel,
fdate: fudate,
cm: cmd,
id: id
},
success: function(result) {
alert('result');
$a = $("#ak").html(result);
}
});
}
$(document).ready(function() {
$("#save").click(function() {
ajaxCallDemo();
});
$("#save2").click(function() {
ajaxCallDemo();
});
});
</script>

Categories