Clone search fields in jquery/ajax - php

I'm new to this forum and I would like to tell you my problem already.
I need a multiple search field, when I go to enter the first letters I get the results through an AJAX call made on a file in php, the problem is that in the second input field that I have cloned the AJAX scan does not work and I do not suggestions come out.
So how can I go about making multiple search fields work?
I am attaching the code to make you understand better. Thank you all.
<div class="cont">
<input type="text" class="form-control search" id="search">
<button id="add" onClick="add()">+</button>
</div>
<table class="table table-hover">
<thead>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>City</th>
<th>Salary</th>
</tr>
</thead>
<tbody id="output">
</tbody>
</table>
function add(){
$("#search").clone().val("").attr("id", "search").appendTo(".cont");
}
$("#search").keyup(function(){
$.ajax({
type:'POST',
url:'search.php',
data:{
name:$(this).val(),
},
success:function(data){
$(".#output").html(data);
return data;
}
});
});
I did as you said, but the ajax call in the second input doesn't work, should I call the ajax function to make it work on the new input? How could I do?
Thanks a lot everyone, I solved it

You need to be identifying a class search .. You are calling an ID which is supposed to be unique
When cloning remove the ID attribute and use addClass('search')
$("#search").clone().val("").addClass("search").appendTo(".cont");
Then change your selector from: $("#search")
To $(".search")
in effect calling any element with the class search on keyup
UPDATE
as #ADyson mentioned in the comment .. You will need to bind the keyup action .. The easiest way to do this is using on() ( from the deprecated .live() ). IE:
$(document).on('keyup', '.search', function(){
FULL SNIPPET:
function add(){
$("#search").clone().val("").addClass("search").appendTo(".cont");
}
$(document).on('keyup', '.search', function(){
alert('Call AJAX');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="cont">
<input type="text" class="form-control search" id="search">
<button id="add" onClick="add()">+</button>
</div>
<table class="table table-hover">
<thead>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>City</th>
<th>Salary</th>
</tr>
</thead>
<tbody id="output">
</tbody>
</table>
Check out the API Documentation for a full list of events handled through .on()

Related

Form action not working with table inside form

I have a table inside a form like this:
<form action="file.php" id="myform" method="POST">
<div class="table-responsive ">
<table class="table table-hover" id="tblDetalle">
<thead class="thead-dark">
<tr>
<th>Id</th>
<th>Name</th>
<th>Quant.</th>
<th>Price</th>
<th>Total Price</th>
</tr>
</thead>
<tbody">
<?php
if(!isset($_SESSION['products'])){
}else{
foreach($_SESSION['products'] as $product=>$details){
echo '
<tr class="txtMult">
<th scope = "row">'.$details["code_product"].'</th>
<th scope = "row">'.$details["name_product"].'</th>
<td><input class="val2" type="number" id="quantity" name="quantity" min="1" max="100"></td>
<td class="val1">'.$details["price"].'</td>
<td><span class="multTotal">0.00</span></td>
</tr>
';
};
}
?>
</tbody>
<tfoot>
<tr class="font-weight-bold">
<td colspan=4>Total <span id="grandTotal">0.00</span></td>
<td></td>
</tr>
</tfoot>
</table>
<input type="submit" value="Submit"/>
</div>
</form>
My actual problem is that submit botton isn't working, no actions are taken when I click button.
My idea is send all content of table to file.php through POST method.
There's a script that updates last with price*quantity but I don't think that problem lives there.
<script type="text/javascript">
$(document).ready(function () {
$(".txtMult input").keyup(multInputs);
function multInputs() {
var mult = 0;
// for each row:
$("tr.txtMult").each(function () {
// get the values from this row:
var $val1 = parseInt($('.val1', this).text())
var $val2 = $('.val2', this).val();
var $total = ($val1 * 1) * ($val2 * 1)
$('.multTotal',this).text($total);
mult += $total;
});
$("#grandTotal").text(mult);
}
});
</script>
Anybody can help? :)
Once the small typo in the HTML is corrected and without your PHP logic ( no way to test that - hence hardcoded dummy data ) what you could do would be to use Javascript to send the form data rather than rely upon a regular form submission as was failing for you here. HTML content and text will not be sent via the form - only content from input elements so your form would submit a single field called quantity which is not what you want.
The following uses fetch to send the formData to your intended PHP script.
$(document).ready(function () {
function multInputs() {
var mult = 0;
$("tr.txtMult").each(function () {
var $val1 = parseInt($('.val1', this).text())
var $val2 = $('.val2', this).val();
var $total = ($val1 * 1) * ($val2 * 1)
$('.multTotal',this).text($total);
mult += $total;
});
$("#grandTotal").text(mult);
return mult;
}
const submithandler=(e)=>{
// stop the regular `submit`
e.preventDefault();
// add form data to these variables
let fd=new FormData();
let payload=[];
// process the contents of the HTML table to populate the formData object
$("tr.txtMult").each(function(){
let item={
code:this.firstElementChild.textContent,
name:this.firstElementChild.nextElementSibling.textContent,
value:$('.val2', this).val()
};
// convert object to string
payload.push( JSON.stringify(item) );
});
fd.set('payload', payload );
// send the request
fetch( document.getElementById('myform').action,{ method:'post', body:fd })
.then( r=>r.text() )
.then( text=>{
alert( text )// do stuff with results?
})
.catch( err=>console.log('Error:%o',err) )
};
$(".txtMult input").keyup(multInputs);
$('[type="submit"]').click(submithandler);
});
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="file.php" id="myform" method="POST">
<div class="table-responsive ">
<table class="table table-hover" id="tblDetalle">
<thead class="thead-dark">
<tr>
<th>Id</th>
<th>Name</th>
<th>Quant.</th>
<th>Price</th>
<th>Total Price</th>
</tr>
</thead>
<tbody>
<!-- Hardcoded example data -->
<tr class="txtMult">
<th scope = "row">Code ABC-1</th>
<th scope = "row">Name - 1</th>
<td><input class="val2" type="number" name="quantity" min="1" max="100"></td>
<td class="val1">100</td>
<td><span class="multTotal">0.00</span></td>
</tr>
<tr class="txtMult">
<th scope = "row">Code ABC-2</th>
<th scope = "row">Name - 2</th>
<td><input class="val2" type="number" name="quantity" min="1" max="100"></td>
<td class="val1">200</td>
<td><span class="multTotal">0.00</span></td>
</tr>
<tr class="txtMult">
<th scope = "row">Code ABC-3</th>
<th scope = "row">Name - 3</th>
<td><input class="val2" type="number" name="quantity" min="1" max="100"></td>
<td class="val1">300</td>
<td><span class="multTotal">0.00</span></td>
</tr>
</tbody>
<tfoot>
<tr class="font-weight-bold">
<td colspan=4>Total <span id="grandTotal">0.00</span></td>
<td></td>
</tr>
</tfoot>
</table>
<input type="submit" />
</div>
</form>
It is possible to use tables inside forms but I think you're approach is wrong. you can put a table inside a form or vice versa, and it is often useful to do so. But you need to understand what you are doing.
Tables and forms can be nested either way. But if you put forms into tables, each form must be completely included into a single table cell (one TD element in practice). Thereby the forms are each completely independent.
So try putting the form inside the table cell which requires the input

Display data from console log

I am trying to display database into an html page. The data appears in my console but I cant figure out how to display it in an html table. I am not sure the function I need to add into console.log (data) for it to display onto to the page. This is what I have so far:
<button class="btn btn-primary" id="btn">Get Code</button>
<table class="table table-bordered">
<thread>
<tr>
<th>ID</th>
<th>City</th>
<th>Country</th>
<th>Rating</th>
</tr>
</thread>
<tbody id ="tdata">
</tbody>
</table>
<script>
$(function () {
$.getJSON("php.php", {tableName:"travel"}, function(data){
if (data["code"] == "error"){
console.log(data["message"]);
}
else{
console.log(data);
}
console.log("returned hh");
});
});
console.log("returned");
</script>
</body>
</html>
Its no json structure example so you will have to replace "value.a" with the correct json values names.
After json is loaded:
$.each(data,function(i,value){
$('.table').append('<tr><td>value.a</td><td>value.b</td><td>value.c</td><td>value.d</td></tr>')
})
Hope this helps

Resized Page - Button submitting and not using jquery

Update, seems it is also happening when i go onto the next page (fullscreen this time).
I'm hoping someone could possible help me as this has been driving me crazy. I have a table full off orders which each row has a button. This button when submitted will show an alert.
I am using data-tables (Responsive), and when the table is all on the screen, the button works as intended. However, when the screen is resized and the button goes within the + icon to expand the row. The button is not running the jquery and is submitting the page.
I have no idea how to fix this and was wondering if there is a workaround. Here is a sample of the code if it helps.
<table id="datatable-buttons" class="table table-striped table-bordered dt-responsive nowrap" cellspacing="0" width="100%">
<thead>
<tr>
<th>Order Number</th>
<th>Button</th>
</tr>
</thead>
<tbody>
<?php foreach ($orders as $order): ?>
<tr>
<th scope="row">
<?php echo $order['OrderNumber']; ?>
</th>
<td>
<form id="<?php echo $order['OrderNumber']; ?>">
<input type="submit" value="Submit">
</form>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
At the bottom of the page:
<?php foreach ($orders as $order): ?>
<script>
$('#<?php echo $order['OrderNumber']; ?>').on('submit', function () {
alert('Form submitted!');
return false;
});
</script>
<?php endforeach; ?>
Any help would be appreciated! I have no idea why it isn't working when the table is resized.
Use a delegated event handler instead :
$('#datatable-buttons').on('submit', '#<?php echo $order['OrderNumber'];?>', function() {
alert('Form submitted!');
return false;
});
Your event handler does not work because the form not exists in dom at the time of declaration.
But all those dedicated #id based event handlers is completely unnecessary. A single (delegated) handler is sufficient :
$('#datatable-buttons').on('submit', 'form', function () {
alert('Form ' + $(this).attr('id') + ' submitted!');
return false;
});
Hey mate you could try something like this for the alert
<table id="datatable-buttons" class="table table-striped table- bordered dt-responsive nowrap" cellspacing="0" width="100%">
<thead>
<tr>
<th>Order Number</th>
<th>Button</th>
</tr>
</thead>
<tbody>
<?php foreach ($orders as $order): ?>
<tr>
<th scope="row">
<?php echo $order['OrderNumber']; ?>
</th>
<td>
<button type="button" class="btnPress" id="<?php echo $order['OrderNumber']; ?>">Submit</button>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
Bottom
<script>
$('.btnPress').on('click', function () {
alert('Form submitted!');
alert(this.id);
});
</script>

A way to add to a table on the fly that could have the values removed [duplicate]

I have construted my table as follows:
<table id="dataTable">
<thead>
<tr><th>Name</th>
<th>Value</th></tr>
</thead>
<TR><TD>Scooby Doo</TD><TD>6</TD><TD><INPUT TYPE="Button" onClick="AddRow()" VALUE="Add Row"></TD></TR>
</table>
When the button Add Row is clicked, I need to change the button to a delete button and insert a new row on the first line. The first line must contain the same as in the code. How can I do this?
On clicking the delete button, Imust be able to delete the row to which the delete button belong?
Hope this helps
$(function(){
$("input[type='button'].AddRow").toggle(
function(){
var el = $(this);
el.closest('tr').clone(true).prependTo(el.closest('table'));
el.attr("value", "Delete row");
},
function(){
$(this).closest('tr').remove();
});
});
<table id="dataTable" border="1">
<thead>
<tr>
<th>
Name
</th>
<th>
Value
</th>
</tr>
</thead>
<tr>
<td>
Scooby Doo
</td>
<td>
6
</td>
<td>
<input type="Button" value="Add Row" class="AddRow">
</td>
</tr>
</table>
Working Demo
Something like?
$('#dataTable thead').prepend('<tr><th>Name</th><th>Value</th></tr>');
And for the deleting:
$('#dataTable thead tr').click(function() {
$(this).hide(); //hide the row, this doesn't delete it.
});
.

Passing table data with post variables

Basically I have a table with a bunch of numbers coming from a database with columns for totals/subtotals. I do not intend to add any of the totals to the database, but I need to pass the total numbers from one page to the next. I can't seem to properly pass them as post variables using PHP... I'm wondering if this is a bad tactic firstly, secondly what should I do instead?
And if this is possible, how would I go about doing it? I haven't been able to derive the text between the < td >'s from using $_POST['tdname'].
Example code:
<form method="POST" action="newcivilreport2.php">
<div style="width:800px;text-align:left;margin:0 auto;padding-bottom:5px;">A. PENDING BALANCE</div>
<table border="1" style="width:800px;" ID="tableA">
<th style="width:40%;"></th>
<th style="width:15%;">Civil</th>
<th style="width:15%;">Asbestos</th>
<th style="width:15%;">Domestic</th>
<th style="width:15%;">Total</th>
<tr>
<td>1. Pending Balance from Previous Month</td>
<td id="PendingCivil" name="PendingCivil">66</td>
<td id="PendingAsbestos">0</td>
<td id="PendingDomestic">0</td>
<td id="PendingTotal">0</td>
</tr>
</table>
<input type="submit" value="Save and Continue -->"></form></div>
newcivilreport2.php:
<?php
$_POST['PendingCivil'];
?>
POST will only send inputs like <input type='text|file|hidden|ect' />. Perhaps you would like to use AJAX. For example:
<table id="tData">
<tbody>
<tr>
<td class='dataVal1'>100</td>
...
$(document).ready(function() {
var toServer = {};
var data = $('#tData tbody tr td').each(function(key, value) {
toServer[$(this).attr('id')] = $(this).text();
});
$.ajax({
url: 'page.php',
data: toServer,
type: 'POST'
})
});
The <td> tag of a table does not provide values for a form.
Use a hidden field for your post:
http://www.w3schools.com/tags/att_input_type.asp
...
<td>1. Pending Balance from Previous Month</td>
<td id="PendingCivil">66<input type="hidden" name="PendingCivil" value="66"></td>
...
Also, is it inside of a form?

Categories