my for loop is creating this at run time using jquery
<tr id="auctionLocation_0"></tr>
<tr id="auctionLocation_0"></tr>
<tr id="auctionLocation_0"></tr>
<tr id="auctionLocation_1"></tr>
<tr id="auctionLocation_1"></tr>
<tr id="auctionLocation_1"></tr>
and I'm removing it using jquery each loop and my code is
function testing() {
var current = 0;
$("#user").each(function() {
$("#user").find("tr[id='auctionLocation_"+current+"']").remove();
current++;
});
}
OR
function testing() {
$("#user").each(function(i, v) {
$("#user").find("tr[id='auctionLocation_"+i+"']").remove();
});
}
its only remove 0 index not 1 index so how I could do it?
thats my creating code
var counterForLocationsField = 1;
var auctionCompanyLocationArray = data.auctionCompanyLocationArray;
for(var auctionCompanyLocationLoop = 0; auctionCompanyLocationLoop < auctionCompanyLocationArray.length; auctionCompanyLocationLoop++) {
var completeTr = "<tr id='auctionLocation_"+auctionCompanyLocationLoop+"'><td>Location Name "+counterForLocationsField+"</td><td>"+auctionCompanyLocationArray[auctionCompanyLocationLoop]["auctionLocationName"]+"</td> <td>Location Address "+counterForLocationsField+"</td><td>"+auctionCompanyLocationArray[auctionCompanyLocationLoop]["auctionLocationAddress"]+"</td></tr>";
completeTr += "<tr id='auctionLocation_"+auctionCompanyLocationLoop+"'><td>Location City "+counterForLocationsField+"</td><td>"+auctionCompanyLocationArray[auctionCompanyLocationLoop]["auctionLocationCity"]+"</td> <td>Location State "+counterForLocationsField+"</td><td>"+auctionCompanyLocationArray[auctionCompanyLocationLoop]["auctionLocationState"]+"</td></tr>";
completeTr += "<tr id='auctionLocation_"+auctionCompanyLocationLoop+"'><td>Location Zipcode "+counterForLocationsField+"</td><td>"+auctionCompanyLocationArray[auctionCompanyLocationLoop]["auctionLocationZipcode"]+"</td> <td>Location Phone "+counterForLocationsField+"</td><td>"+auctionCompanyLocationArray[auctionCompanyLocationLoop]["auctionLocationPhone"]+"</td></tr>";
$(completeTr).insertBefore("#lastRow");
counterForLocationsField++;
}
As you select the id user, the loop only loops once. Ids are unique.
You can use the starts with selector.
$("tr[id^='auctionLocation_']").remove();
No loop needed. If you want to loop use $("tr[id^='auctionLocation_']").each().
Do not use same ids for different elements. Id must be unique in the page.
Use class instead, like:
<tr class="auctionLocation_0"></tr>
<tr class="auctionLocation_0"></tr>
<tr class="auctionLocation_0"></tr>
<tr class="auctionLocation_1"></tr>
<tr class="auctionLocation_1"></tr>
<tr class="auctionLocation_1"></tr>
And when you want to remove them, just do the above, without loops:
$('tr.auctionLocation_0').remove()
Related
I have a table with a double click event on every each of the rows. When I double click on any row, it will display another row called ".matching". Besides that, I also want to create a column rowspan if a hidden ".matching" row is displayed. Below shows my php part:
<table>
<tr ondblclick="rowdoubleclick(this);">
<td>...</td>
<td>...</td>
<td class="lastcolumn">Rowspan is here</td>
</tr>
<tr class="matching" style="display:hidden;">
<td colspan="2">Hidden row shows here</td>
</tr>
</table>
And this is my jquery:
function rowdoubleclick(e) {
var tablerow = $(e).closest('tr');
var rowammend = $('.lastcolumn');
var matching = $(e).closest('tr').next('tr.matching');
if(matching.is(":hidden")) {
tablerow.attr('rowspan','2').css({'border-bottom':'transparent'});
matching.slideToggle("fast");
rowammend.attr('rowspan','2');
}
else {
tablerow.css({'border-bottom':'1px solid #939393'});
matching.hide();
rowammend.attr('rowspan','1');
}
}
The problem with this code, when i double click on any row, it creates the rowspan on another row. Or in another word, it create all rowspan to all of the rows in the table.
How to add particular column rowspan to that particular double click row event?
Try this, You should find lastcolumn of clicked row
function rowdoubleclick(e) {
var tablerow = $(e).closest('tr');
// here you should find from clicked row and not from each row
var rowammend = $(e).find('.lastcolumn');
var matching = $(e).closest('tr').next('tr.matching');
if(matching.is(":hidden")) {
tablerow.attr('rowspan','2').css({'border-bottom':'transparent'});
matching.slideToggle("fast");
rowammend.attr('rowspan','2');
}
else {
tablerow.css({'border-bottom':'1px solid #939393'});
matching.hide();
rowammend.attr('rowspan','1');
}
}
I've been working in a project where I need to dynamically fill a table according with what I select from two combobox, so the problem is that I need to take those values to save them on the database but I can't find a way to do this.
The code when I press the button:
<input type="button" name="btnAgregarPrograma" value="Agregar" onClick="addRow()"/>
function addRow()
{
var dep = $("#cbxDependencia").val();
var pro = $("#cbxPrograma").val();
if(dep == 0 || pro == 0)
alert('Debe seleccionar una dependencia y un programa para poder agregarlos'); //Traslation: you must select a dependency and a program to continue
else
{
$.get("funciones/agregarProDep.php",{pro: pro},
function(resultado)
{
if(resultado == false)
{
alert("Error");
}
else
{
$("#table_depProg").attr("disabled",false);
var row = $("<tr>" + resultado + "</tr>");
$('#table_depProg').append(row);
}
}
);
}
}
As you can see, the code above calls a php file with the next code
<?php
include("funciones.php");
$pro = 0;
$programas = agregarProgramaDependencia($_GET["pro"]);
foreach($programas as $fila)
{
echo ("
<td id=".$fila['idPrograma'].">".$fila['Nombre']."</td>
<td><input type='button' value='Eliminar' onclick='borrarFila(this)'</td>
");
}
?>
That's the way I fill the table, but now I just can't find a way to get the contained data when I submit the page to get and save the data, I would apreciate any help.
I tried to explain the best I could, if something is not clear just let me know and I will answer back with a better explanation.
I know this is an old question, but I ran into the same thing and here is what I did.
Created a DataRow object that contained the fields of each row
Iterated through the table's rows (skipping the header) and stored each row in a DataRow and pushed it onto an Array.
Used JSON.Stringify to convert the Array to JSON
Stored the JSON in a <input type="hidden"> so it would get POSTed.
Here is the HTML example:
<table border="2px solid black">
<tr id="header-row">
<th>Dx Code</th>
<th>Dx Date</th>
<th>OnSet Or Ex</th>
</tr>
<tr>
<td>3022</td>
<td>1/1/2014</td>
<td>ONSET</td>
</tr>
<tr>
<td>V9099</td>
<td>1/21/2014</td>
<td>EX</td>
</tr>
<tr>
<td>1199</td>
<td>1/31/2014</td>
<td>ONSET</td>
</tr>
</table>
<br />
<input type="button" value = "Submit" id="out">
JavaScript:
// object to hold your data
function dataRow(value1,value2,value3) {
this.dxCode = value1;
this.dxDate = value2;
this.dxType = value3;
}
$('#out').click(function(){
// create array to hold your data
var dataArray = new Array();
// iterate through rows of table
// * Start from '2' to skip the header row *
for(var i = 2; i <= $("table tr").length; i++){
// create object and push to array
dataArray.push(
new dataRow(
$("table tr:nth-child(" + i + ") td").eq(0).html(),
$("table tr:nth-child(" + i + ") td").eq(1).html(),
$("table tr:nth-child(" + i + ") td").eq(2).html())
);
}
var sJson = JSON.stringify(dataArray);
alert(sJson);
})
Finally, JSFiddle to see it: http://jsfiddle.net/leisenstein/vy3ux/
I have php code that creates a table. For each item on the purchase order a new row is created and populated. The goal is when the purchase order is edited it gets posted back and saved in the database. Everything is working except my jQuery code will only iterate over the first row for however many rows I have. (So if I have three rows it will print the first rows cartid three times.)
Sorry if things look messy.
PHP Code:
<?php while($row = mysql_fetch_array($itemsquery)){?>
<tr class="item-row" id="<?php echo $row['cart_id']?>">
<td class="item-name"><div class="delete-wpr"><textarea><?php echo $row['on0'];?> <?php echo $row['itemname'];?></textarea><a class="delete" href="javascript:;" title="Remove row">X</a></div></td>
<td class="description"><textarea class="cartid"><?php echo $row['cart_id'];?></textarea></td>
<td><textarea class="cost" class="text-input" type="text"><?php echo $row['itemprice'];?></textarea></td>
<td><textarea class="qty" type="text" name="name"><?php echo $row['quantity'];?></textarea></td>
<td><span class="price" type="text">$<?php
$linecost = $row['quantity'] * $row['itemprice'];
echo $linecost;?></span></td>
</tr>
<?php }?>
jQuery statement to see what it has grabbed:
$(document).ready(function(){
$(".item-row").change(function() {
$((".cartid")).each(function(){
row = {
cartid: $(".cartid").val()
}
alert(row.cartid);
performAjaxSubmission();
})
});
It looks like you just have your selectors mixed up. You are wanting to iterate over each of the rows, but your selector is referencing $(".cartid"), which would always return the first result ever time.
This should fix your problem:
$(document).ready(function(){
$(".item-row").change(function() {
$(".item-row").each(function(){
var rowContext = $(this);
var row = {
cartid: $(".cartid", rowContext).val()
}
alert(row.cartid);
performAjaxSubmission();
});
});
You have extra () in your .cartid selector.
$(document).ready(function(){
$(".item-row").change(function() {
$(".cartid").each(function(){
row = {
cartid: $(".cartid").val()
}
alert(row.cartid);
performAjaxSubmission();
})
});
Also, shoudn't you be looping trough .item-row instead of .cartid?
You're iterating like this:
$(".cartid").each(function(){
row = {
cartid: $(".cartid").val()
}
Seems like you should be doing
$(".cartid").each(function(){
row = {
cartid: $(this).val()
}
Haven't checked the rest of the code.
EDIT:
$(".cartid").each(function(){
var cart = $(this);
row = {
cartid: cart.val()
}
Problem no 1 Why my table do not align?
Problem no 2 Why everytime I click my Warrior List at the nav the output goes like this
Here's my js
function getWarriors() {
$.ajax({
url: 'display_warrior.php',
success: function(data) {
$('#listWarriors').append(data);
}
});
}
Here's my html
<article id="listWarriors">
<h1>Warrior List</h1>
<table>
<tr>
<th colspan="2">Warriors</th>
</tr>
<tr>
<td>Warrior Name</td>
<td>Warrior Type</td>
</tr>
</table>
</article>
And heres my php
foreach($result as $names){
$warriors['wname'] = $names['warrior_name'];
$warriors['wtype'] = $names['warrior_type'];
echo '<tr>
<td>'.$warriors['wname'].'</td>
<td>'.$warriors['wtype'].'</td>
</tr>';
}
the result is appended under the </table>
try change your ajax success to :
$('#listWarriors table').append(data);
for number2, im affraid it's truncated by the container (#listWarriors)..
check your css of that id if the width is fixed or not...make it wider as you please
The way you have your jQuery, you are appending the content to the '' tag, and not to the table.
This is what happens when each item is appended, with the way its setup (I added a thead tag by the way. Will come in handy once you start styling your table)
This is the output when things are appended, and why its rendering wrong.
<article id="listWarriors">
<h1>Warrior List</h1>
<table>
<thead>
<tr>
<th colspan="2">Warriors</th>
</tr>
<tr>
<td>Warrior Name</td>
<td>Warrior Type</td>
</tr>
</thead>
</table>
<tr>
<td>the wname</td>
<td>the wtype</td>
</tr>
</article>
With that said modify your jquery to
$('#listWarriors table').append(data);
By the way,
How many items are you wanting to append. If you will make multiple ajax calls and append things one at a time, I would recommend getting the data through JSON. Let me know, if I can help
AS DISCUSSED IN COMMENTS SINCE YOU WANT TO GET MULTIPLE ITEMS JSON IS THE WAY TO GO. You can pass data using JSON this way
**The php (Im sure you already have the query already done but here it is just in case) **
// Make a MySQL Connection
$query = "SELECT * FROM example";//Your query to get warriors from db
$result = mysql_query($query) or die(mysql_error());
$myWarriorsArray = array();//Where you will store your warriors
while($row = mysql_fetch_array($result)){
$myWarriorsArray[] = $row;
//This stores all keys for each iteration
/*//This is teh same as the following commented code
$myWarriorArray['warrior_name'] = row['warrior_name'];
$myWarriorArray['warrior_type'] = row['warrior_type'];
*/
}
echo json_encode($myWarriorsArray);//This will return a json object to your ajax call
The Javascript
function getWarriors() {
$.ajax({
url: 'display_warrior.php',
dataType : 'json',
success: function(data) {
var toAppend = '';
alert(data);
//console.log(data);//Uncomment this to see the returned json data in browser console
for(var i=0;i<data.length;i++){//Loop through each warrior
var warrior = data[i];
toAppend += '<tr>';
toAppend += '<td>'+data[i]['warrior_name']+'</td>';
toAppend += '<td>'+data[i]['warrior_type']+'</td>';
toAppend += '</tr>';
}
$('#listWarriors table').append(toAppend);
}
});
}
I have json array return as bellow
{"id":16,"minutes":146}
{"id":17,"minutes":137}
{"id":18,"minutes":123}
{"id":22,"minutes":84}
I'm trying to render above json array inside table tbody td which json array id's equal to td id's and display the minutes inside td tag
for example json id :16 minute:146 and display it in <td id="16">146</td>
<table>
<thead>
<tr>
<th>op</th>
<th>Minutes</th>
</tr>
</thead>
<tbody>
<tr>
<td>op1</td>
<td id="16">0</td>
</tr>
<tr>
<td>op2</td>
<td id="17">0</td>
</tr>
<tr>
<td>op3</td>
<td id="18">0</td>
</tr>
<!--....and goes on -->
</tbody>
</table>
js
$.ajax({ url: statUrl, type: 'POST',
data: {
begin: begin,
end: end
},
success: function(data){
}
});
Your JSON is invalid it should only represent one object, a valid version of what you have will be
[{"id":16,"minutes":146},
{"id":17,"minutes":137},
{"id":18,"minutes":123},
{"id":22,"minutes":84}]
If your data IDs directly correspond to already existing DOM element IDs then it should be rather easy:
for (var i = 0; i < data.length; i++) {
$('#' + data[i].id).text(data[i].minutes);
}
This is using jQuery ofc.
you can use json_decode($json, true) in php to convert the json to an array then loop over it's elements and build your table.
If you want to do it client side, I think you must create table, tr and td elements manually and populate them. ExtJS has ready grid for this.
Server side is easier.
I created a jsFiddle here: http://jsfiddle.net/5pKjW/11/
As Musa stated, the JSON you posted is not valid, it should be an array containing all the objects.
The code following is basically what you need to do inside the success callback, just use data instead of result.
What I do is creating a table, appending a row for every element of the array and then appending the whole table to an element of the DOM.
var result = [{"id":16,"minutes":146},{"id":17,"minutes":137},{"id":18,"minutes":123},{"id":22,"minutes":84}];
var $table = $('<table><thead><tr><th>op</th><th>Minutes</th></tr></thead>'),
$tbody = $('<tbody>').appendTo($table),
i;
for (i = 0; i < result.length; i++){
$tbody.append('<tr><td>op' + (i+1) + '</td><td id="' + result[i].id + '">0</td></tr>');
}
$table.appendTo('#container');
As T.J. Crowder commented, a valid HTML4 id attribute can't start with a digit. If I were you, I would prefix it with a string (<td id="prefix' + result[i].id + '">0</td>).
MrOBrian suggested to use a rendering engine. Maybe for a simple case like this, and if you don't need a rendering engine elsewhere, it's an overkill, but that's absolutely something worth considering, if you need something more complicated in the future.
as suggested fixed json array to
{
"25":72.3833,
"17":116.3167,
"16":25.75,
"34":28.3333,
"29":136.8831,
"19":40.9166,
"32":43.6,
"22":83.9001
}
and js
$.getJSON(statUrl, {begin: begin, end: end}, function(data) {
$.each(data, function(key, val) {
$('#op_' + key).text(Math.ceil(val));//also fixed td id
});
});
so got the result as expected.
thanks for your time.