This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 6 years ago.
I have this table:
<table id="product" class="table table-bordered table-striped">
<thead>
<tr>
<th>Id</th>
<th>Cantidad</th>
<th>Producto</th>
<th>Marca</th>
<th>Precio</th>
<th>Importe</th>
<th>Serial</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
I add rows to that table with this jquery code:
$( "#name" ).autocomplete({
source: 'http://sosacelulares.com/index.php/product/search',
minLength: 1,
select: function (event, ui) {
var value = ui.item.value;
var data1 = value.split("-");
var data = data1[0].split(" ");
$( "#product" ).show();
var v = data[1];
$.ajax({
async:true,
type: "POST",
dataType: "html",
contentType: "application/x-www-form-urlencoded",
url:"http://sosacelulares.com/index.php/product/get",
data:"id="+v,
success: function(response) {
var returnedData = JSON.parse(response);
$("#product > tbody").append('<tr><td>' + returnedData[0].id_product + '</td><td><input min="1" type="number" style="width: 100px;" value="" class="form-control quantity" id="quantity" placeholder="Cantidad" required></td><td>' + returnedData[0].name + '</td><td>' + returnedData[0].brand + '</td><td><input type="text" style="width: 100px;" value="' + returnedData[0].buy_price + '" class="form-control" placeholder="Precio" required></td><td></td><td><button type="submit" class="btn btn-success">Agregar Serial</button></td></tr>');
}
});
},
});
I just look for a name in a text input and then when I find it I just add it to the table. The problem is that the rows that I am adding they have a number input field that it is to add the quantity I test it like this:
$(".quantity").change(function () {
alert(1);
});
I do not know why if I change the quantity input that it is ubicated within the new row that i added with jquery it does not work, if I make a change the alert does not appear, what am I doing bad? Thanks!
Try this:
$(document).on("change", ".quantity", function () {
alert(1);
});
Related
Here is my jquery function. i call this function on blue event. there are more than one records in list. i want particular rojmel_id and weight on blur event but i am not able to get. can anyone help me in this issue.
<script type="text/javascript">
function getweight(thisObj)
{
var row = $(thisObj).parents('.row');
var rojmel_id = row.find('.rojmel_id').val() != '' ? row.find('.rojmel_id').val() : 0;
var dataString = "rojmel_id=" + rojmel_id;
$.ajax({
type: "POST",
url: "updateWt.php",
data: dataString,
success: function (data){
}
});
}
</script>
Here is my html code
{section name=sec loop=$clientArray}
<tr>
<td>{$clientArray[sec].rojmel_date}</td>
<td>{$clientArray[sec].party_name}</td>
<td>{$clientArray[sec].item_nm}</td>
<td>{$clientArray[sec].marko}</td>
<td><input type="hidden" class="rojmel_id" name="rojmel_id" value="{$clientArray[sec].rojmel_id}">
<input type="text" name="weight" value="{$clientArray[sec].weight}" onblur="getweight(this);"></td>
</tr>
{/section}
</tbody>
Try this hope it work! and can you tell where you have been declared .row class.
Here is your solution: Solution JSBin
<!-- add class to <tr> then -->
{section name=sec loop=$clientArray}
<tr class="row">
<td>{$clientArray[sec].rojmel_date}</td>
<td>{$clientArray[sec].party_name}</td>
<td>{$clientArray[sec].item_nm}</td>
<td>{$clientArray[sec].marko}</td>
<td><input type="hidden" class="rojmel_id" name="rojmel_id" value="{$clientArray[sec].rojmel_id}">
<input type="text" name="weight" value="{$clientArray[sec].weight}" onblur="getweight(this);"></td>
</tr>
{/section}
</tbody>
<script type="text/javascript">
function getweight(thisObj)
{
var row = $(thisObj).closest('tr.row');
var rojmel_id = row.find('.rojmel_id').val() ? row.find('.rojmel_id').val() : 0;
var dataString = "rojmel_id=" + rojmel_id;
$.ajax({
type: "POST",
url: "updateWt.php",
data: dataString,
success: function (data){
}
});
}
</script>
I am trying to alert something but on click function is running only once on the first button. but I have buttons on many rows.
I am fetching Data through Laravel from Database in a table. Only one button runs a function, then nothing happens with other buttons.
Jquery:
jQuery(document).ready(function(e) {
$('#restore-data').on('click', function(e) {
var val = $("#thisr").attr('value');
alert(val);
});
});
View:
<table id="recover-table" class="table" >
<thead>
<tr class="bg-info">
<th>Teacher Name</th>
<th>Date</th>
<th>Action</th>
</tr>
</thead>
<tbody>
#foreach($trashs as $trash)
<tr id="thisr" value="{{$trash->id}}">
<td class="text-nowrap ">{{$trash->efirst}} {{$trash->esecond}}</td>
<td class="text-nowrap ">{{$trash->deleted_at}}</td>
<td class="text-nowrap "><button type="submit" class="" name="id"
value="{{$trash->id}}" id="restore-data">Delete</button></td>
</tr>
#endforeach </tbody></table>
Right now even alert is not working, but I want to achieve Refresh table after a record is deleted from Table.
Update: Now Alert is working fine, but when I delete a record by pressing a button, only one row is deleting. the function runs once.
Complete Js:
jQuery(document).ready(function(e) {
$('#restore-data').on('click', function(e) {
let teacher_id=$(this).attr('value');
console.log('Restore button clicked!')
e.preventDefault();
$.ajax(
{
url: "/teachers/recover/" + $('#restore-data').attr("value"),
type: 'GET', // Just delete Latter Capital Is Working Fine
headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },
data: teacher_id,
success: function (data) {
console.log(data.msg);
console.log(teacher_id);
if(data.msg){
$('#thisr').remove();
$('#response').empty();
$(".toast").toast('show');
$('#response').append(data.msg);
}
},
error: function (xhr) {
console.log("Error Restoring Record");
//console.log(xhr.responseText);
},
});
});
});
You can try to use class 'restore-data'
$(document).ready(function(e) {
$(document).on('click', '.restore-data', function(e) {
var val = $('#thisr').val();
alert(val);
});
});
As id should be unique for each element.
You can try something like
#foreach($trashs as $trash)
<tr>
<td class="text-nowrap ">{{$trash->efirst}} {{$trash->esecond}}</td>
<td class="text-nowrap ">{{$trash->deleted_at}}</td>
<td class="text-nowrap ">
<button type="button" data-trash-id="{{$trash->id}}" class="restore-data">Delete</button>
</td>
</tr>
#endforeach
and JS as
$(document).on('click', '.restore-data', function(e) {
var trash_id = $(this).attr('data-trash-id');
alert(trash_id);
});
Change this line.
var val = $("#thisr").attr('value');
to (since you have value attribute in button):
var val = $(this).attr('value');
or (since you have value attribute td):
var val = $(this).parent('tr#thisr').attr('value')
To remove a row.
$('#restore-data').on('click', function(e) {
var _this = $(this);
...
if(data.msg){
_this.parent('tr#thisr').remove();
....
Also change button type to button.
<button type="button" class="" name="id"
value="{{$trash->id}}" id="restore-data">Delete</button></td>
You gave same id to all button and id must be unique of particular button so you can define unique id with key of array and pass it to Function
#foreach($trashs as $key=>$trash)
<tr id="thisr{{$key}}">
<td class="text-nowrap ">{{$trash->efirst}} {{$trash->esecond}}</td>
<td class="text-nowrap ">{{$trash->deleted_at}}</td>
<td class="text-nowrap ">
<button type="button" class="" name="id" value="{{$trash->id}}" id="restore-data{{$key}}" onclick="restoreData({{$key}})">Delete</button>
</td>
</tr>
#endforeach
function restoreData(key){
var val = $("#restore-data"+key).attr('value');
alert(val);
// you can use either
$("#restore-data"+key).closest('tr').remove();
// OR
$('#thisr'+key).remove();
}
I have a table that generating dynamic raw's, I need to send through ajax post to receive from PHP. Below I have given all my selected codes, this is not working.
In console showing as
PHP ERROR: Undefined index all_ch_no, all_yd_stock_no, all_comments
HTML FORM, below table rows are dynamically generated through ajax, if I place static table data, then it's working! How can I solve?
<form method="post" id="customer_do_add">
<input type="text" id="phone_no" name="phone_no">
<table class="table" id="group_cars">
<thead>
<tr>
<th style="width: 20%;">Chassis No</th>
<th style="width: 15%;">Yard Stock No</th>
<th style="width: 50%;">Comments</th>
<th style="width: 15%;">Remove</th>
</tr>
<tr>
<td><input type="text" class="waz" value="DD51T-224534" name="all_ch_no[]"></td>
<td><input type="text" class="waz" value="77832" name="all_yd_stock_no[]"></td>
<td><input type="text" class="waz" value="Test3" name="all_comments[]"></td>
</tr>
<tr>
<td><input type="text" class="waz" value="DD51T-45354" name="all_ch_no[]"></td>
<td><input type="text" class="waz" value="123123" name="all_yd_stock_no[]"></td>
<td><input type="text" class="waz" value="Test" name="all_comments[]"></td>
</tr>
...
</thead>
</table>
</form>
jQuery:
$('#customer_do_add').on('submit', function(e) {
e.preventDefault();
var val = $('#customer_do_add').serializeArray();
$.ajax({
url: "auction/customer_do_add/",
data:val,
type: "POST",
success: function (responseText, statusText, xhr, $form) {
result = $.parseJSON(responseText);
}
});
return false;
});
PHP
public function customer_do_add(){
print_r($_POST);
exit;
}
Printing Only Phone number, Arrays are not printing
Array
(
[phone_no] => 123456
)
Send data params in Jquery call then only you can receive post
$('#customer_do_add').on('submit', function(e) {
e.preventDefault();
var val = $('#customer_do_add').serializeArray();
$(this).ajaxSubmit({
url: "auction/customer_do_add/",
data: val,
success: function (responseText, statusText, xhr, $form) {
result = $.parseJSON(responseText);
}
});
return false;
});
Your $_POST is empty because jQuery.ajax() will pass data as GET data (it's being appended to the url). Setting the method arg to post will fix this.
$.ajax({
url: "/auction/customer_do_add/",
data: val,
success: function (data) {
console.log(data);
},
dataType: 'json',
method: 'POST',
});
You could also use jQuery.post() for a simplified syntax;
$.post({
url: "/auction/customer_do_add/",
data: val,
success: function (data) {
console.log(data);
},
dataType: 'json'
});
I'm stuck in multiple input. My code is not showing all data. below is the html I am using:
<form id="matkul" class="form-horizontal" method="POST">
<table class="table table-condensed">
<thead>
<tr>
<th>Matakuliah</th>
<th>Data Lain</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</form>
<button id="post" type="submit">Save</button>
<button id="get">Get Data!</button>
below is the code to get the data
<script>
$(document).ready(function() {
$("#get").click(function() {
var url = 'https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20html%20where%20url%3D%22https%3A%2F%2Funisys.uii.ac.id%2Fuii-ras%2Fmatakuliah.asp%3Fidx%3D1%26session_id%3DxxbKiKJawuyrbaaiJ3Kabybabi3JJiKJrJyb3wiuKbbry0JbKiKbKr0yyrKK15933511%26no_mhs%3D%22&format=json';
$.getJSON(url,
function(data) {
var id = data.query.results.body.table.tr.td.table.tr[2].td.table.tr;
for (var i = 1; i <= id.length; i++) {
$("<tr> <td> <input name='fmatakuliah' value='"+id[i].td[1].a.content+"'> </td> <td> <input name='fdata' value='" + id[i].td[1].a['href'] + "'> </td> </tr>").appendTo("#matkul tbody");
};
});
});
});
</script>
from the above code output will be
Matakuliah Data Lain
StringOne OtherData
StringTwo OtherData
below is the ajax post code, but when it is already sending the data, the alert does not show all the data
<script type="text/javascript">
$(document).ready(function(){
$("#post").click(function(){
string = $("form").serialize();
alert(string); // this alert is normal, show all data
$.ajax({
type: "GET",
url: "/save.php",
data: string,
success: function(data){
alert("Success!"+data); //this not normal, not show all data
}
});
});
});
</script>
below is the code on save.php
print_r($_GET);
The latest response is showing like this
Array
(
[fmatakuliah] => Wide Area Network
[fdata] => matakuliahdetail.asp?session_id=xxbKiKJawuyrbaaiJ3Kabybabi3JJiKJrJyb3wiuKbbry0JbKiKbKr0yyrKK15933511&mk=52323605&kur=2010
)
My question is how to show all data and save it to the database?
It looks like you need to change the AJAX type from GET to POST:
$.ajax({
type: "POST",
url: "/save.php",
data: string,
success: function(data){
alert("Success!"+data); //this not normal, not show all data
}
});
I want to pass label/value pair in Ajax .POST but cannot find any solution. Ajax .POST normally send id/value pair but I cannot change my id and would like to send labels/value pair instead. I have provided partial form. Any help please.
$.ajax({
url:"allfields.php",
type:"POST",
// dataType:"json",
data: $("#frmRequest").serialize(),
success: function(msg){
alert("Form Submitted: "+ msg);
return msg;
},
error: function() {
alert('Error occured');
}
});
<body>
<form id="frmRequest" name="frmRequest" >
<div class="clearfix" id="idRequestDetails" >
<table width="809" border="0" id="tbl_data_1_1_1_1__" summary="Profile">
<tr>
<th width="156" scope="col"><label class="labelrequest" for="txtProfileName1__">Name</label>
</th>
<th width="74" scope="col"><label class="labelrequest" for="txtProfileUserID1__">User ID</label></th>
<th width="131" scope="col"><label class="labelrequest" for="txtSiteCost1__">Site Cost Centre</label></th>
<th width="182" scope="col"><label class="labelrequest" for="txtDetail1__">Additional Details</label></th>
</tr>
<tr>
<td><input type="text" name="txtProfileName1__" id="txtProfileName1__" tabindex="100" /></td>
<td><input name="txtProfileUserID1__" type="text" class="clearfix" id="txtProfileUserID1__" tabindex="110" size="8" /></td>
<td><input name="txtSiteCost1__" type="text" id="txtSiteCost1__" tabindex="220" size="8" /></td>
<td><textarea name="txtDetail1__" rows="1" id="txtDetail1__" tabindex="240"></textarea></td>
</tr>
</table>
</div>
</body>
Here is an example:
HTML
<form>
<label>Label1</label><input type="text" value="1">
<label>Label2</label><input type="text" value="some">
</form>
jQuery
var dataToServer = [];
$('form label').each(function() {
dataToServer.push({
label: $(this).text(),
value: $(this).next().val()
});
});
console.log(data);
// output
// [ {label: 'Label1', value: '1'}, {label: 'Label2', value: 'some'}]
Working Example.
Hope this can give you some guideline.
According to commnet
AJAX part
$.ajax({
url: "allfields.php",
type: "POST",
dataType:"json",
data: dataToServer, // send above data here
success: function(msg) {
alert("Form Submitted: " + msg);
return msg;
},
error: function() {
alert('Error occured');
}
});
Final shot
$('#submit').on('click', function() {
var dataToServer = [];
$('#frmRequest label').each(function(i, el) {
var temp= {},
label = $(this).text(),
value = $('#' + $(this).attr('for')).val();
temp[label] = value;
dataToServer.push(temp);
});
console.log(dataToServer);
});
See the console output