I have this PHP in my application,
<table><tr>
<?php
if($music_interests !== FALSE)
{
$count = 0;
foreach($music_interests as $interest)
{
?>
<td>
<div class="interest inline">
<img src="<?php echo $interest['image']; ?>" alt="<?php echo truncate($interest['name'], 25); ?>" class="interest_img"/>
<p><?php echo truncate($interest['name'], 25); ?></p>
<div class="interest_popup">
<img src="<?php echo $interest['image']; ?>" alt="<?php echo truncate($interest['name'], 25); ?>" class="interest_img left"/>
<div class="right">
<strong><?php echo truncate($interest['name'], 25); ?></strong>
<p>Music<br><?php echo #$interest['num_users']; ?> users have this interest.</p>
<?php echo anchor('my_profile/remove_interest/'.$interest['id'], 'Remove interest', array('class' => 'button red upper rounded_5 small remove')); ?>
</div>
<div class="clear"></div>
</div><!--.interest_popup-->
</div>
</td>
<?php
$count = ($count + 1)%4;
if ($count == 0)
{
echo "</tr><tr>";
}
}
}
?>
As you can see the PHP creates a table and every 4th <td> creates a new row. I am now adding ajax functionality to my app, but I cannot work out how I would work out if I need to create a new row first before appending a <td> that my ajax request has created.
Currently I have this code that adds a td to my table,
var interest = "<td>" + msg.name + "</td>";
self.parent().children('table').append(interest);
You shouldn't append table cells directly into the table. Table cells goes into table rows.
Get the last row in the table, and check how many cells there are in it. If there are four cells already you need to create a new table row and append to the table, then add the cell to that row. Otherwise you can add the cell to the existing row.
Warnign! untested code! I would do something like this:
var interest = "<td>" + msg.name + "</td>";
var $lastTr = self.parent().children('table tr:last');
if ($lastTr.find("td").size() < 4) {
$lastTr.append(interest);
} else {
interest = "<tr>" + interest + "</tr>";
self.parent().children('table').append(interest);
}
Update: I modified the answer since now I have better understanding of the question.
Here's a sample that shows how you can dynamically create td and tr elements. Replace the constant content ("some value") with whatever you get using AJAX.
JSFiddle (jQuery 1.7.1 added): http://jsfiddle.net/BUR7p/3/
<html>
<head>
<script language="javascript" type="text/javascript">
//my previous understanding of the question
//function AddNewRow()
//{
// var row = $(document.createElement("tr"));
// row.append("<td>some value</td>");
// row.append("<td>another val</td>");
// $("#mytable").children().append(row);
//}
//my corrected understanding: you don't know how
//to decide how to create a new row to put in the
//table. note i added a table body explicitly, it
//is added by default automatically if you don't.
function AddNewData()
{
var row = $("#tablebody").children().last();
if(row.children().length >= 4)
{
console.log("creating a new row...");
//create a new row if we need one
row = $(document.createElement("tr"));
$("#tablebody").append(row);
}
else console.log("using existing row...");
//add new datum to row
row.append("<td>some value</td>");
}
</script>
</head>
<body>
<p>
<table id="mytable">
<tbody id="tablebody">
<tr>
<td>one</td>
<td>two</td>
</tr>
<tr>
<td>three</td>
<td>four</td>
</tr>
</tbody>
</table>
</p>
Add new row
</body>
</html>
As an alternative, you can modified the server side in a way that returns, in addition to the data, a flag whether the data should be created in a new row or not.
Please follow up and tell us if this helps or not.
answer found at this question:
// pass stuff to insert to .after() as an HTML string
$('#myTable tr:last').after('<tr>...</tr><tr>...</tr>');
documentation for :last psuedoselector and .after() function
Related
I'm still new with yii
and now I want to add a Javascript code that can append dropdown list to the table, when I click the button.
Here is my table:
<table class="table table-hover" id="table-add-more">
<tr>
<th style="width:50px;">No</th>
<th style="width:200px;">Name</th>
<th style="width:50px;">Count</th>
<th style="width:30px;"></th>
</tr>
<tbody>
</tbody>
</table>
Here is my button:
<a id="btn-add-more" class="btn btn-sm btn-success">Add More</a>
Here is my script:
<script>
$(document).ready(function(){
var number = 1;
var product = <?php $product = Product::model(); echo $form->dropDownList($product,'ID', CHtml::listData(Product::model()->findAll(), 'ID', 'name')); ?>;
$('#btn-add-more').click(function() {
var more_field = "<tr>"+
"<td>"+number+"</td>"+
"<td>"+
<?php echo "product"; ?>
+"</td>"+
"<td><input type='number'/></td>"+
"<td><input type='checkbox'/></td>"+
"</tr>"
$('#table-add-more').append(more_field);
number = number + 1;
});
});
</script>
I got an error message:
"unexpected token <"
near the var product = <select name="Product[ID]" id="Product_ID">
but I can't found the mistake yet.
Please help..
I think the better way is to have dropdown list with display: none at initialization and when you click that button, you can change display to block. But If you want to append dropdown to your table, I think you have tow problem in your javascript function:
1.You need to wrap this php code into "".
var product = "<?php $product = Product::model(); echo $form->dropDownList($product,'ID', CHtml::listData(Product::model()->findAll(), 'ID', 'name')); ?>";
I think you need to have <?php echo $product; ?>, instead of <?php echo "product"; ?>
My question might be confusing, basically I have two tables in my ordering, one which is connected to a mysql database displaying the items i have in stock and the other (empty) table is where all my selected items go.
pic: http://tinypic.com/r/o89pn5/8
Now, everytime i click the button beside each row on the top table, it transfers the rows to the lower table
pic: http://tinypic.com/view.php?pic=290sfw2&s=8#.U7LMjpSSzTo
Now notice on the lower table I have another column named "Quantity". Can anyone show me how to fill this column with textboxes? Thanks a lot to anyone who can help me. I'm just staring to learn Javascript/JQuery.
Please feel free to ask me more questions in case my question is not clear.
Code for the tables:
<!-- Table 1(inventory table) -->
<?php
$con=mysqli_connect("localhost","root","","purchasing");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM tbl_inventory");
echo "<table id='table1' class='inventory' border='3'>
<tr>
<th>Check</th>
<th>ID</th>
<th>Product Name</th>
<th>Price</th>
<th>Stock</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td> <button class='btn'>order</button> </td>";
echo "<td>" . $row['prod_id'] . "</td>";
echo "<td>" . $row['prod_name'] . "</td>";
echo "<td>" . $row['price'] . "</td>";
echo "<td>" . $row['stock'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
<br/><br/>
<!-- Table 2(ordered items table) -->
<table id="table2" class="inventory" border="3">
<tr>
<th>Check</th>
<th>ID</th>
<th>Product Name</th>
<th>Price</th>
<th>Stock</th>
<th>Quantity</th>
</tr>
<tbody>
</tbody>
</table>
The scripts:
<script>
$(".btn").click(function () {
// get the row containing this link
var row = $(this).closest("tr");
// find out in which table it resides
var table = $(this).closest("table");
// move it
row.detach();
if (table.is("#table1")) {
$("#table2").append(row);
}
else {
$("#table1").append(row);
}
// draw the user's attention to it
row.fadeOut();
row.fadeIn();
});
</script>
After this line:
$("#table2").append(row);
just append textbox in last tr last td like this:
$("#table2").find("tr:last").find("td:last").append('<input type="text" class="quantity" />');
JQuery gives you a few different ways to dynamically add elements to the page. In this case, if you wanted to add a text input to a td element you could do something simple like this:
<script>
$('table#table2 td.quantity').append('<input type="text" name="quantity" id="quantity" value="0" />");
</script>
You can also build elements using various JQuery methods and then append the the JQuery object directly:
<script>
var inputObj = $('<input />');
inputObj.attr('type','text').val('0').attr('name','quantity').attr('id','quantity');
$('table#table2 td.quantity').append( inputObj );
</script>
Hopefully, this may work, but it won't remember whichever value has been put in the text box if a user removes the row from #table2 and put it back later on.
if (table.is("#table1")) {
row.append('<td><input type="text" class="quantity" /></td>');
$("#table2").append(row);
}
else {
row.find('td:last').remove();
$("#table1").append(row);
}
If you have good html5 support, you should be able to use inputs of type number instead of a plain text box.
As an extra, you probably want to have the fadeout/fadein happen around the row move. You may implement it as follow:
var row = $(this).closest('tr');
var table = $(this).closest('table');
row.fadOut(300, function(){
row.detach();
if (table.is("#table1")) {
row.append('<td><input type="text" class="quantity" /></td>');
row.find('.btn').html('remove');
$("#table2").append(row);
}
else {
row.find('td:last').remove();
row.find('.btn').html('order');
$("#table1").append(row);
}
row.fadeIn(300);
});
Actually, I have created this table:
<table border='0' name="codes">
<tr>
<td><b> <?php echo xlt('Code'); ?> </b></td>
<td><b> <?php echo xlt('Description'); ?> </b> </td>
</tr>
<? php ...... ?>
</table>
Due to the fact that the size of the table is dynamic ,I have a counter ($counter) that counts the rows of the table including the first row that shows the columns of the table (Code Description).
I also have created a button "Erase" and when I press it I want it to delete the table.
Below there is the code of the button "Erase":
<input type='button' value='<? php echo xla('Erase'); ?>' onclick="selcode(**' <? php echo $counter; ?>'**)" />
The button "Erase" calls the function selcode and inside this function there will be the code that delete the table. The function selcode is written in Javascript.
<script language="JavaScript">
function selcode(counter) {. . . }
</script>
Can you help me please how can I delete the table? Also, the way I enter the php variable counter as function parameter is the right one?
Change the erase button to type="reset" this will wipe out your form and clean it.
<input type='reset' value='< ? php echo xla('Erase'); ?>'>
I think thats what you are wanting?
Something like:
function selcode() {
var el = document.getElementsByName("codes")[0];
el.parentNode.removeChild(el);
return false;
}
I am currently building an internal tool for viewing and editing SQL-like tables via the web. I have some PHP and html written that generates these tables and jQuery written that does this, so far:
Delete Rows
Add New Rows
Output form value after entry
The ultimate goal, of course, is to generate a SQL statement using INSERT, UPDATE, DELETE, etc on the modified data. I have a grasp on how to concatenate the results into such a statement, but could use help targeting columns for it.
My main concern is modifying the form value output function so that I can store any updated entries in an array and output them as a CSV string. I've read about .each, .map, .push, and .serializeArray. I'm not sure exactly how to use/combine these methods to accomplish the desired result. Here are some code snippets:
The current jQuery:
$('#add_row').on('click', function(){
$('<tr><td id="data"><input class ="new_row"></td><td id="data"><input class ="new_row"></td><td id="data" style="text-align:center;"><input class ="new_row"></td><td id = "Delete_Button"><button class="rmv_row">-</button></td></tr>').appendTo('#SQLdata');
});
$("table").on('keyup', 'input', function(){
$('#output').text($(this).val());
});
$('table').on('click', '.rmv_row', function(){
$(this).closest('tr').remove();
});
});
and the PHP/HTML:
<table id="SQLdata">
<tr style="background-color: margin-left:#6b685c;">
<td style="background-color: margin-left:#6b685c; font-family:tahoma,arial,verdana,sans-serif"; colspan="3">
<form style="color:black;" method="post" action="WebEventsStructureColumnTool.php">
Select your table name:
<select method="post" name="table_name" id="picker">
<option>Removed For Security</option>
</select>
<input type="submit" value="Go" name="submit">
</form>
</td>
<td><button id="add_row">Add a Row</button></td>
</tr>
$tableName = $_POST['table_name'];
$statementObject = $pdo->prepare("SELECT a, b, c FROM tab WHERE _id =?");
$statementObject->bindParam(1, $tableName, PDO::PARAM_STR);
$statementObject->execute();
$statementObject->bindColumn('a', $Col1);
$statementObject->bindColumn('b', $Col2);
$statementObject->bindColumn('c', $Col3);
while ($statementObject->fetchAll(PDO::FETCH_BOUND)){
// Gets an array from the CSVs in the column :
$Column1 = explode(",", $Col1);
$Column2 = explode(",", $Col2);
$Column3 = explode(",", $Col3);
}
//Fetches the total number of values from each exploded array:
$Count1 = count($Column1);
$Count2 = count($Column2);
$Count3 = count($Column3);
//Establishes the total length/height of the table:
$largest = $Count1;
if ($Count2 > $largest){
$largest = $Count2;
}
if ($Count3 > $largest){
$largest = $Count3;
}
echo '
<tr>
<th>a</th>
<th>b</th>
<th style="text-align: center">c</th>
<th>delete row</th>
</tr>';
for($i = 0; $i < $largest; $i++){
$tableRows[] =
"<tr>
<td id='data'>
<input type='text' value='" . $Column1[$i] . "'>
</td>" .
"<td id='data'>
<input type='text' value='" . $Column2[$i] . "'>
</td>" .
"<td id = 'data' style='text-align:center;'>
<input type='text' value='". $Column3[$i]. "'>
</td>
<td id = 'Delete_Button'><button class='rmv_row'>-</button></td>";
}
foreach ($tableRows as $row){
echo $row;
}
echo '</table><div><table><tr id="output" colspan="4"></tr></table>'
If anyone also has advice/recommendations on existing code, feel free to criticize. I am a young developer just starting out and could use all the help I can get. Thanks!
I added this bit this morning and am now successfully getting CSVs:
var string = new Array()
function updateString(){$('#output').text(string);}
$('input').each(function(){
string.push($(this).val());
});
Working on creating three different arrays for each data manipulation option and limiting printing to conditionals.
I'm trying to grab the cell values from an HTML table so that I can save them into a MySQL table via a call to PHP. I'd like to use JavaScript rather than jQuery.
I'm giving each TR a distinct ID based on the MySQL table's ID field. Also, each TD input cell has a unique ID based on the MySQL table's ID field. Not sure if I need all those, but I used them.
How do I grab the cell's value so that I can pass it to a PHP procedure(I know how to code this PHP) to save the data into MySQL? My JavaScript code below grabs the "innerHTML" but I need to grab the cell value's instead.
For example, if I have 3 rows of data from a MySQL table, with fields id and amount, with values below, how do I grab the "3" and the "1.99"?:
id amount
-------------
1 100.00
2 9.99
3 1.99
Here is a sample of the PHP/HTML code for the table, submit button and onclick call:
(this is a very simplified version of my actual code but should convey the idea)
<?php
/* define mysql database connect, query and execute it returning result set into $result, id=integer primary key, is_active=tinyint(0 or 1), amount=decimal(12,2) */
/* ... */
/* output form/table */
echo "<form id='myform' name='myform' >" ;
echo "<table id='mytable' name='mytable'>" ;
while($row = mysql_fetch_array($result))
{
$id = $row['id'] ;
$amount = $row['amount'] ;
$tr_id = "tr_id_" . trim((string)$id) ;
$td_id = "td_id_" . trim((string)$id) ;
$td_amount_id = "td_amount_id_" . trim((string)$id) ;
$input_amount_id = "input_amount_id_" . trim((string)$id) ;
echo "<tr id='$tr_id' name='$tr_id'>";
echo "<td id='$td_id_account' > $id </td>" ;
echo "<td id='$td_amount_id' > <input type='text' id='$input_amount_id' value=$amount > $amount </td>" ;
echo "</tr>";
}
echo "</table>";
echo "</form>" ;
/* submit button and onclick call */
echo "<br />" ;
echo "<table>";
echo "<tr>" ;
echo "<td>";
echo "<button type='button' " . 'onclick="SubmitTableData(\'' . "mytable" .'\');"' . ">Submit</button>" ;
echo "</td>" ;
echo "</tr>";
echo "</table>";
?>
And here is a sample of my JavaScript function used to loop through the rows of the HTML table:
function SubmitTableData(TableID)
{
var table = document.getElementById(TableID);
for (var i = 0, row; row = table.rows[i]; i++)
{
// iterate through rows
for (var j = 0, col; col = row.cells[j]; j++)
{
// iterate through columns
alert(col.innerHTML);
}
/* call PHP procedure with row's cell values as parameters */
/* ... */
break;
}
}
Use the innerText property for the td. Here's a fiddle that shows how to use it.
HTML
<table>
<tr>
<td id="1">Bla</td>
<td id="2"><input id="txt" />Ble</td>
</tr>
</table>
JavaScript
var td = document.getElementById('1');
alert(td.innerText);
var td2 = document.getElementById('2');
alert(td2.innerText);
How to grab cell values from a table?
Update to address Elliots comment
See how to grab the cell value (innerText and data-value) in my new demo
In the table the attribute data-value is used to store some data (2B, 3C,..).
<table id="t2">
<thead>
<tr id="tr1"><th>Student Name<th>Course</tr>
</thead>
<tbody>
<tr id="tr2"><td data-value="2B">Bert2 <td>Economics </tr>
<tr id="tr3"><td data-value="3C">Clyde3 <td>Chemics </tr>
<tr id="tr4"><td data-value="4D"> <td>Digital Art</tr>
<tr id="tr5"><td data-value="5E">Ernest <td>Ecmoplasma </tr>
</tbody>
</table>
With jQuery and the right selector you can iterate over each cell:
function eachCell(){
var cellInnerText = [];
var cellValue = [];
var out = document.getElementById("out");
var out2 = document.getElementById("out2");
// iterate over each row in table with id t2 in the table-body (tbody)
$('#t2 tbody tr').each(function(index){
// copy the text into an array
cellInnerText.push($(":first-child", $(this)).text());
//copy the data-value into an array
cellValue.push($(":first-child", $(this)).attr('data-value'));
});
// show content of both arrays
out.innerHTML = cellInnerText.join(" | ");
out2.innerHTML = cellValue.join(" | ");
}
Alert the innerHTML of the first cell in the table's first row
<!DOCTYPE html>
<html>
<head>
<style>
table, td {
border: 1px solid black;
}
</style>
</head>
<body>
<p>Click the button to alert the innerHTML of the first cell (td element with index 0) in the table's first row.</p>
<table id="myTable">
<tr>
<td>Row1 cell1</td>
<td>Row1 cell2</td>
</tr>
<tr>
<td>Row2 cell1</td>
<td>Row2 cell2</td>
</tr>
<tr>
<td>Row3 cell1</td>
<td>Row3 cell2</td>
</tr>
</table>
<br>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
alert(document.getElementById("myTable").rows[0].cells[0].innerHTML);
}
</script>
</body>
</html>
Place IDs on Your inputs with some pattern. for example <input type="text" id="input_0_0" name="whatever" /> where 0 is row and second 0 is column and then instead your alert type
v = document.getElementById('input_'+row+'_'+col).value;
It should help You get rolling now