Im having troubles with showing the data that i want in the tables. I did the following sketch so you guys can figure out what i want to display:
The query i have in my php/mysql connector brings me each "Tarea" data(second table) with "proyecto" and "alerta" but i need to display "proyecto" and "alerta" only 1 time per row.
So i did this in angular to storage the data of the second table(Tarea, Termino, Estado, Nombre), while i display the data of the first table.
scope.llamada1 = function() {
$http.get("conector.php?tipoDato=query1")
.then(function(response) {
$scope.mensajeEspera = "";
$scope.datos1 = response.data;
for(var i = 0; i < $scope.datos1.length; i++){
var currentObj = $scope.datos1[i];
$scope.datos1[i].detalleProyecto = [{
"tarea":currentObj.tarea ,
"fecha_termino":currentObj.fecha_termino ,
"estado":currentObj.estado,
"nombre_completo":currentObj.nombre_completo}];
}
});
}
And in the html i get the data like this, with the table inside the last :
<table id="tablaTareas" class="table table-striped table-bordered" >
<thead>
<tr>
<td><b>Proyecto</b></td>
<td><b>Alerta</b></td>
<td><b>Tareas</b></td>
</tr>
</thead>
<tbody>
<tr ng-repeat="x in datos1 ">
<td style="vertical-align: top;">{{x.proyecto}}</td>
<td style="vertical-align: top;">{{x.alerta}}</td>
<td style="vertical-align: top;">
<table class="table table-striped table-bordered" >
<thead>
<tr>
<td><b>Tarea</b></td>
<td><b>Termino</b></td>
<td><b>Estado</b></td>
<td><b>Responsable</b></td>
</tr>
</thead>
<tbody>
<tr ng-repeat="y in x.detalleProyecto track by $index">
<td>{{y.tarea}}</td>
<td>{{y.fecha_termino}}</td>
<td>{{y.estado}}</td>
<td>{{y.nombre_completo}}</td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
But is repeating "Proyectos" and "Alerta" and displaying 1 "Tarea" per row and not every task together per proyect and alert, an example below.
you should try to arrange your data this way
[
{
name: nombre_completo,
data: [
{
tarea,
fecha_termino,
estado
}
]
}
]
where name is the repeated data that you don't want to repeat
a little example
if you have data like
[{country: Chile, name: Martin},{country: Chile, name: Nico},{country: Peru, name: Seba},{country: Peru, name: Nicole},{country: Argentina, name: Warencita}]
try this (assuming var datos is where your data is stored)
var datos = [{country: 'Chile', name: 'Martin'},{country: 'Chile', name: 'Nico'},{country: 'Peru', name: 'Seba'},{country: 'Peru', name: 'Nicole'},{country: 'Argentina', name: 'Warencita'}]
var temp = []
var exists
var place
for(var i = 0; i < datos.length; i++){
exists = false;
for(var k = 0; k < temp.length; k++){
if(datos[i].country === temp[k].country){
exists = true;
place = k;
break;
}
}
if(exists){
temp[place].data.push({
name: datos[i].name
})
}else{
temp.push({
country: datos[i].country,
data: [{
name: datos[i].name
}]
})
}
}
Related
I am using Ajax request to fetch data from database. All I want to do is to display the result in tabular form whenever we select an option from the option list. I am also able to do that but when I am choosing another option the view for the previous option it is not removed from the table.
View:
$('#city').on('change',function(){
var cityID = $(this).val();
// alert(cityID);
$.ajax({
type:'POST',
url:'<?php echo base_url('bank/getBranchDetail'); ?>',
data:'city_id='+cityID,
success:function(data){
var dataObj = jQuery.parseJSON(data);
$(dataObj).each(function(){
var ifsc = $('<p />');
var micr = $('<p />');
var contact = $('<p />');
var address = $('<p />');
// alert(option);
ifsc.attr('value', this.id).text(this.ifsc_code);
micr.attr('value', this.id).text(this.micr_code);
contact.attr('value', this.id).text(this.contact_no);
address.attr('value', this.id).text(this.address);
$('#ifsc').append(ifsc);
$('#micr').append(micr);
$('#contact').append(contact);
$('#address').append(address);
});
// $('#hodm_results').html(data);
}
});
});
<table class="table table-bordered table-hover table-full-width" id="table_userinfo">
<thead>
<tr>
<th>IFSC Code</th>
<th>MICR Code</th>
<th>Contact No.</th>
<th>Address</th>
</tr>
<tr>
<td id="ifsc"></td>
<td id="micr"></td>
<td id="contact"></td>
<td id="address"></td>
</tr>
</thead>
</table>
Controller:
public function getBranchDetail(){
$branch = array();
$city_id = $this->input->post('city_id');
if($city_id){
$con['conditions'] = array('id'=>$city_id);
$branchData = $this->Bank_model->getBranchData($con);
}
echo json_encode($branchData);
}
Model:
function getBranchData($params = array()){
$this->db->select('c.micr_code, c.ifsc_code, c.contact_no, c.address');
$this->db->from($this->branchTbl.' as c');
//fetch data by conditions
if(array_key_exists("conditions",$params)){
foreach ($params['conditions'] as $key => $value) {
if(strpos($key,'.') !== false){
$this->db->where($key,$value);
}else{
$this->db->where('c.'.$key,$value);
}
}
}
$query = $this->db->get();
$result = ($query->num_rows() > 0)?$query->result_array():FALSE;
//return fetched data
return $result;
}
When I am selecting a city from option it is showing me the result for that city which is correct. When I am choosing another city from the option it is showing the result also, but the result for the previous option is not removed from the table. I want to remove the previous record when I am selecting another option.
Check the below code ( not tested ). Clear the contents before appending data in the loop.
$('#city').on('change',function(){
var cityID = $(this).val();
// alert(cityID);
$.ajax({
type:'POST',
url:'<?php echo base_url('bank/getBranchDetail'); ?>',
data:'city_id='+cityID,
success:function(data){
var dataObj = jQuery.parseJSON(data);
// clear the data before appending
$('#ifsc').html("");
$('#micr').html("");
$('#contact').html("");
$('#address').html("");
$(dataObj).each(function(){
var ifsc = $('<p />');
var micr = $('<p />');
var contact = $('<p />');
var address = $('<p />');
// alert(option);
ifsc.attr('value', this.id).text(this.ifsc_code);
micr.attr('value', this.id).text(this.micr_code);
contact.attr('value', this.id).text(this.contact_no);
address.attr('value', this.id).text(this.address);
$('#ifsc').append(ifsc);
$('#micr').append(micr);
$('#contact').append(contact);
$('#address').append(address);
});
// $('#hodm_results').html(data);
}
});
});
<table class="table table-bordered table-hover table-full-width" id="table_userinfo">
<thead>
<tr>
<th>IFSC Code</th>
<th>MICR Code</th>
<th>Contact No.</th>
<th>Address</th>
</tr>
<tr>
<td id="ifsc"></td>
<td id="micr"></td>
<td id="contact"></td>
<td id="address"></td>
</tr>
</thead>
</table>
I'm new in Jquery and I want once the user adds new row and give the important information once he clicks on "Ajouter" button it will add on data base then reload the table automatically.
Once i run that I found that the data added successfully to the database however "tablebqup" does not reload anymore and it I found this error :
Uncaught TypeError: Cannot set property '_DT_CellIndex' of undefined
Here is the function to add the new element:
$("#newbq").click(function () {
var indexadd= $('table#tablebqup tr:last').index() + 1;
//Now add this row to the table:
var row='<tr><td></td><td contenteditable="true"></td><td contenteditable="true"></td><td contenteditable="true"></td><td contenteditable="true"></td><td contenteditable="true"></td><td colspan="2"> <button id="add'+indexadd+'" class="btn btn-info addbc" name="button">Ajouter</button> </td></tr>';
$('#tablebqup').append(row);
$(".addbc").click(function () {
var nombc=($(this).parent().parent().find('td:eq(1)').html());
var abrv= ($(this).parent().parent().find('td:eq(2)').html());
var sigsoc=($(this).parent().parent().find('td:eq(3)').html());
var telf=($(this).parent().parent().find('td:eq(4)').html());
var fx=($(this).parent().parent().find('td:eq(5)').html());
// if (nombc=="" || abrv=="" || sigsoc=="" || (telf=="" && fx==""))
if (nombc=="")
{
alert("Rempier toutes les informations de la banque d'abord")
}
else {
$choix=confirm("voulez vous vraiment ajouter la banque");
if ($choix)
{
console.log(nombc);
$.post(basUrl+'views/component/updtbq.php',
{
action:'add_bq',
nomb:nombc,
abrvb:abrv,
sigsocial:sigsoc,
tel:telf,
fax:fx,
}, function(data) {
alert(data);
$('#tablebqup').DataTable().ajax.reload();//My problem is here
});
}
}
});
});
In the fist time one i run it it showed something like this :
“Uncaught TypeError: $(…).DataTable is not a function”
To solve it i added the appropriate link and script:
Doing that the error has changed to :
Uncaught TypeError: Cannot set property '_DT_CellIndex' of undefined
What surprised me that i have used above similar logic I mean use the same:
$('#tablebqup').DataTable().ajax.reload();
and once I click another button just to modify information on data base in this way :
$(".modif").click(function () {
$choix=confirm("voulez vous vraiment sauvegarder les modifications");
if ($choix)
{
var id=($(this).parent().parent().find('td:eq(0)').html());// the value in the 1st column.
var nombc=($(this).parent().parent().find('td:eq(1)').html());
var abrv= ($(this).parent().parent().find('td:eq(2)').html());
var sigsoc=($(this).parent().parent().find('td:eq(3)').html());
var telf=($(this).parent().parent().find('td:eq(4)').html());
var fx=($(this).parent().parent().find('td:eq(5)').html());
console.log(id);
$.post(basUrl+'views/component/updtbq.php',
{
action:'update_bq',
idbc:id,
nomb:nombc,
abrvb:abrv,
sigsocial:sigsoc,
tel:telf,
fax:fx,
}, function(data) {
$('#tablebqup').DataTable().ajax.reload();
});
}
That work perfectly without adding any of this two links!!!
Here is the dtail of the error:
Uncaught TypeError: Cannot set property '_DT_CellIndex' of undefined
at Ga (datatables.min.js:36)
at M (datatables.min.js:28)
at HTMLTableRowElement.<anonymous> (datatables.min.js:28)
at jquery-3.2.1.min.js:2
at Function.map (jquery-3.2.1.min.js:2)
at r.fn.init.map (jquery-3.2.1.min.js:2)
at ma (datatables.min.js:28)
at e (datatables.min.js:104)
at HTMLTableElement.<anonymous> (datatables.min.js:104)
at Function.each (jquery-3.2.1.min.js:2)
Here is my php file:
function add_bq()
{
if((isset($_POST['nomb']))
&&(isset($_POST['abrvb']))
&&(isset($_POST['sigsocial']))
&&(isset($_POST['tel']))
&&(isset($_POST['fax']))
){
$nomb=trim($_POST['nomb']);
$abrv=trim($_POST['abrvb']);
$sigc=trim($_POST['sigsocial']);
$tel=trim($_POST['tel']);
$fax=trim($_POST['fax']);
//Update les banques
MainController::addBanque($nomb,$abrv,$sigc,$tel,$fax);
include 'C:/wamp/www/Mini_Prj/views/component/tbbanqueupd.php';
}
and here is the included:"tbbanqueupd.php":
<?php
require_once("C:/wamp/www/Mini_Prj/controllers/mainController.php");
$bnqs=MainController::getBanque();
echo'
<div>
<h3> Mise a jours des banques</h3>
<div >
<div class="table-responsive">
<table id="tablebqup" class="tableau table table-fixed table-bordered table-dark table-hover ">
<thead>
<tr>
<th>Id Banque</th>
<th>Nom de la banque</th>
<th>Abrev </th>
<th>Siège Sociale</th>
<th>Tel</th>
<th>Fax</th>
<th>Modifier</th>
<th>Supprimer</th>
</tr>
</thead>
<tbody>
<form method="post">
';
$i=0;
foreach ($bnqs as $bnq) {
echo
" <tr>
<td>".$bnq['idbc']."</td>
<td contenteditable='true'>".$bnq['nomb']."</td>
<td contenteditable='true'>".$bnq['abrvb']."</td>
<td contenteditable='true'>".$bnq['sigsocial']."</td>
<td contenteditable='true'>".$bnq['tel']."</td>
<td contenteditable='true'>".$bnq['fax']."</td>
<td> <button id='modif$i' class='btn btn-info modif' name='button'>Modifier</button> </td>
<td> <button id='supp$i' class='btn btn-info supp' name='button' onclick='suprimer(this.id)'>Supprimer</button> </td>
</tr>";
$i++;
}
echo'
</form>
</tbody>
</table>
</div>
<button type="button" class="btn btn-info" name="button" id="newbq" >Nouvelle banque</button>
</div>
</div>';
I thought that maybe the problem is because i allow the user to not filling all the informations, but i want that it gonna be in this way the user enters just the important field.
How could I solve this problem?Can someone help.
It gives me this error when the number of td doesnt match the number of th, or when I use colspan...
Depending on your css, it could be hard to see. I'd add a border to the table while testing it out...
A simple mistake, the table header had a column " with no title, but the column did not exist in the table itself. I could not see it missing (because o no title and no borders).
Was helped by looking at the line in the datatable.js which gave the error - was implying a tr was at fault, so looked more carefully at my table and not my overall code
From your code, I don't see the DataTabe initialization, usually placed inside the Document Ready function. So:
Try to Initialize your table with an explicit configuration for each column ("visible:true" is a dummy setting that just confirms it is visible)
Add the "datatable" class to your table html. Example:
Example:
$(document).ready(function () {
var myTable= $('#tablebqup').DataTable({
columns:[
//"dummy" configuration
{ visible: true }, //col 1
{ visible: true }, //col 2
{ visible: true }, //col 3
{ visible: true }, //col 4
{ visible: true }, //col 5
{ visible: true }, //col 6
{ visible: true }, //col 7
{ visible: true } //col 8
]
});
});
And on the html:
<table id="tablebqup" class="tableau table datatable table-fixed table-bordered table-dark table-hover ">
Explanation:
The "DataTable" initialization method should have the same number of columns on its configuration as the number of <th>'s/<td>'s on your html.
Wrong example:
//Javascript Code
var myTable= $('#myTableId').DataTable({
columns: [
//any column configuration
{ "bSearchable": false }, //col 1
{ "bSearchable": true }, //col 2
{ "bSearchable": true }, //col 3
{ "bSearchable": false }, //col 4
{ "bSearchable": false }, //col 5
{ "bSearchable": false } //col 6
]
});
And the html markup:
<table id="myTable" class="table datatable">
<thead>
<tr>
<th>col 1 header</th>
<th>col 2 header</th>
<th>col 3 header</th>
<th>col 4 header</th>
</tr>
</thead>
<tbody>
<tr>
<td> data col 1, row 1</td>
<td> data col 2, row 1</td>
<td> data col 3, row 1</td>
<td> data col 4, row 1</td>
</tr>
</tbody>
</table>
So even if the number of <td>'s and <tr>'s are matching on the html, having more columns configured on the DataTable method will cause this exception to be thrown. In this example, removing the configuration lines for col 5 and col 6 from the DataTable method would fix the error.
I had correct number of columns in thead-th section and tbody-td section. There was no colspan added on any th or td elements but I was getting the same issue. I did some more research and found that I disabled sorting feature on a column number which was not exist in my data table.
Actually I had only 4 columns in my data table while I was trying to disable sorting feature for 6th number column. It was an accident. I forgot to change it. Code was as:
$(document).ready(function()
{
$('#datatable').DataTable( {
"aoColumnDefs": [
{ 'bSortable': false, 'aTargets': [0,1,6] }
],
responsive: true,
});
});
Then I changed 'aTargets' value, which could be set upto 3 as per my case and correct code was as:
$(document).ready(function()
{
$('#datatable').DataTable( {
"aoColumnDefs": [
{ 'bSortable': false, 'aTargets': [0,1,3] }
],
responsive: true,
});
});
It worked for me. Happy to share and help others :)
I'm building a project with angular and php. I have a "select" option where I choose specific date and it shows me all details in a table, and counting on several things and everything works great. but when I pick a date, i want it to show all results by specific month and not by specific date(for example --> now i choose date like this - '2016-4-15' it will give me all information specific to this date and not by month like i need). can someone please help? in my database the 'date' value is date.
Php query :
$query=" SELECT `description` ,`total_price` , `name`,`supplier_id`,`date` FROM `suppliers`,`expenses`
where `supplier_id` = `refer_supplier_id` ";
Html:
<select ng-model="supplierExpenses.selectedOption" ng-change="setTotals(supplierExpenses)"
ng-options = "item.date for item in supplierExpenses |
unique:'date'" >
<option value="">בחר תאריך</option>
</select>
<div class="table-responsive">
<table class="customer-list table table-striped" >
<thead>
<tr >
<th class="Column-Header">מספר ספק</th>
<th class="Column-Header">שם ספק</th>
<th class="Column-Header">כמות מוצרים שנקנו</th>
<th class="Column-Header">מחיר הוצאה</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="item in supplierExpenses" ng-if = "item.date == supplierExpenses.selectedOption.date"
>
<td>{{item.supplier_id}}</td>
<td>{{item.name}}</td>
<td>{{item.description}}</td>
<td>{{item.total_price}}</td>
</tr>
</tbody>
<tfoot>
<tr class="bg-warning">
<td><font size="6">סה"כ הוצאות</font></td>
<td><font size="6">{{totalExpenses}}</font></td>
<td></td>
</tr>
</tfoot>
</table>
</div>
Controller:
"use strict";
angular.module('dataSystem').controller('supplierExpensesCtrl', function ($scope, $route, $location, $http) {
$http({method:'GET', url:'api/reports-tab/supplier-expenses-by-mounth.php/'})
.then(function(response) {
var arr = JSON.parse(JSON.parse(response.data));
$scope.supplierExpenses = arr;
})
// This will log you the error code and trace, if there is an error.
.catch(function(err) {
console.log('err', err)
});
$scope.totalExpenses = 0;
$scope.setTotals = function(totalItem){
$scope.totalExpenses = 0;
for(var item =0; item< totalItem.length; item++){
// console.log(totalItem[item]);
if (totalItem[item] && (totalItem[item].date == $scope.supplierExpenses.selectedOption.date)){
$scope.totalExpenses += parseInt(totalItem[item].total_price);
}
}
}
});
Hi glad you succeed with the total ^^ I edit my answer with the working solution for the date issue
$http({method:'GET', url:'api/reports-tab/supplier-expenses-by-mounth.php/'})
.then(function(response) {
var arr = JSON.parse(JSON.parse(response.data)), month, date;
for(var i = 0; i< arr.length; i++){
date = new Date(arr[i].date); //we convert the string into javascript date
month = date.getMonth()+1;
if(month.length === 1){
month = '0'+month; //we add a 0 if needed
}
var year = date.getFullYear();
arr[i].date = month+'/'+year; //we use only the month and year
}
$scope.supplierExpenses = arr;
})
how to display this json file using jquery?
[ { "code":"00-002159", "lastname":"SALUNGA", "firstname":"JEFFERSON" },
{ "code":"00-002160", "lastname":"TUMANAN", "firstname":"RHODA" } ]
and look like this
<table>
<thead>
<tr>
<th>code</th> <th>lastname</th> <th>firstname</th>
</tr>
</thead>
<tbody>
<tr>
<td>00-002159</td> <td>SALUNGA </td> <td>JEFFERSON</td>
<td>00-002160 </td> <td>TUMANAN </td> <td>RHODA</td>
</tr>
</tbody>
</table>
jQuery.template should be a good approach to show the data.
Parse json data, the data what you mention in example is array of objects
var data = [ { "code":"00-002159", "lastname":"SALUNGA", "firstname":"JEFFERSON" },
{ "code":"00-002160", "lastname":"TUMANAN", "firstname":"RHODA" } ]
[] - Represents js array an {} - Represents js Object So to parse data and get RHODA use data[0].firstname;
You could try this...
<script type='text/javascript'>
var data = [ { "code":"00-002159", "lastname":"SALUNGA", "firstname":"JEFFERSON" }, { "code":"00-002160", "lastname":"TUMANAN", "firstname":"RHODA" } ];
var string = "";
$.each(data, function() {
$.each(this, function(k, v) {
v += " ";
string += v;
});
});
alert(string);
</script>
see this link also very useful
Loop through JSON object List
I didn't format the string properly , please check that
Assume your json has this format
[ { "code":"00-002159", "lastname":"SALUNGA", "firstname":"JEFFERSON" }, { "code":"00-002160", "lastname":"TUMANAN", "firstname":"RHODA" } ]
Assume you have response in a codes object
var finalHtml='';
finalHtml='<table>
<thead>
<tr>
<th>code</th> <th>lastname</th> <th>firstname</th>
</tr>
</thead>
<tbody>
<tr>'
for(i=0; i< codes.length;i++)
{
//store the values and paint the html
finalHtml+=<td>0codes[i].code;</td> <td>codes[i].lastname </td> <td>JEFFERSON</td>;
}
</tr>
</tbody>
</table>'
append to the dom finally
have some container and do
$('#containerID').html(finalHtml);
Follow this if you can...
Basically i have an order form (which begins with one row).
<form id="orderform" name"orderForm" action="/secure/delivery-details.html" method="post">
<a id="add">+</a>
<table id="ordertable" width="533" border="0" cellspacing="0" cellpadding="2">
<tbody>
<tr>
<td width="33%">Product Code (e.g 66203)</td>
<td width="33%">Mtrs Required (e.g 10)</td>
<td width="33%">Preview Image</td>
</tr>
<tr class="item">
<td class="prodcode"><input type="text" name="prodcode[]" id="prodcode" /></td>
<td class="meterage"><input type="text" name="meterage[]" id="meterage" /></td>
<td class="imgsample"></td>
</tr>
</tbody>
</table>
<button>Submit</button>
</form>
Notice the link with an ID of "add". When checked this adds a new row to the table with the same ID. Using the code below.
var counter = 0;
//Order Form
$("#add").click(function() {
counter++;
var cln = $('#ordertable tbody>tr:last').clone(true);
// cln.find("[id^='prodcode']").each(function(i, val) {
// val.id = val.id.match(/^([^0-9]+)[0-9]*$/)[1] + "" + counter;
// });
cln.insertAfter('#ordertable tbody>tr:last');
$('#ordertable tbody>tr:last input').val('');
$('td.imgsample:last a').remove();
return false;
});
//Check for image preview
$("#prodcode").blur(function() {
var $this = $(this);
$this
.closest('tr') // find the parent tr
.find('td.imgsample') // find the imgsample in the row
.html( $(this).attr('id')) // update the contents
//.animate({'opacity':1},200);
var imgsample = $this.closest('tr').find('td.imgsample')
$.post('/public/themes/lbd/js/searchimage.php', //this page reads the image code and gives you the image location
{ action: 'searchimage', imgreference: $(this).val() },
function(data) {imgsample.html(data);}
);
});
My PHP in searchimage...
When i currently enter a product code if it is invalid it only puts the productID in td.imsample and i want it to say INVALID CODE
//Find image based on Product Code
function findimage($imageToFind) {
require '../../../../config.php';
$dbh = new PDO(DB_DSN, DB_USER, DB_PASS);
$sql = "SELECT * FROM isproducts WHERE prodCode = ".strtoupper($imageToFind)."";
$stmt = $dbh->query($sql);
$obj = $stmt->fetch(PDO::FETCH_OBJ);
$count = $stmt->rowCount();
if($count > 0) {
$sql2 = "SELECT * FROM imageindex WHERE filename LIKE '".strtoupper($imageToFind)."-%'";
$stmt2 = $dbh->query($sql2);
$obj2 = $stmt2->fetch(PDO::FETCH_OBJ);
echo ($stmt2->rowCount() == 1 ? '<span>'.$obj2->path.'/'.$obj2->filename.'</span> -' : 'No Image Available');
} else {
echo 'Invalid Code';
}
}
//Call Function
findimage($_POST['imgreference']);
try this, can have code errors since I could not test at all:
jQuery Template
HTML:
<script id="template-item" type="text/x-jquery-tmpl">
<tr class="item" id="${id}">
<td class="prodcode"><input type="text" name="prodcode[]" class="prodcode-input" data="${id}" val="" /></td>
<td class="meterage"><input type="text" name="meterage[]" class="meterage-input" val="" /></td>
</tr>
</script>
<form id="orderform" name"orderForm" action="/secure/delivery-details.html" method="post">
+
<table id="ordertable" width="533" border="0" cellspacing="0" cellpadding="2">
<thead>
<tr>
<th width="33%">Product Code (e.g 66203)</th>
<th width="33%">Mtrs Required (e.g 10)</th>
<th width="33%">Preview Image</th>
</tr>
</thead>
<tbody>
</tbody>
<tfoot>
<td class="imgsample"></td>
</tfoot>
</table>
<button>Submit</button>
</form>
JS:
$(function() {
var counter = 0;
//Check for image preview
var blur_event = function(ev) {
var
self = $(this),
imgsample = $("#ordertable tfoot .imgsample");
$(imgsample).html( $(this).class() ); // update the contents
$.post('/public/themes/lbd/js/searchimage.php', //this page reads the image code and gives you the image location
{ action: 'searchimage', imgreference: $(self).val() },
function(data) {
$(imgsample).html(data);
}
);
return false;
};
//Order Form
$("#add").bind("click", function(ev) {
counter++;
var cln = $('#template-item').tmpl({id:"item-"+counter);
// cln.find("[id^='prodcode']").each(function(i, val) {
// val.id = val.id.match(/^([^0-9]+)[0-9]*$/)[1] + "" + counter;
// });
$(cln).find(".prodcode-input").bind("blur", blur_event);
$(cln).appendTo('#ordertable tbody');
return false;
});
});
Your problem is most likely due to the duplicated ID. That makes your HTML document invalid. See my explanation here.