I have
var table = "<tr><td><input type='hidden' class='hid_id' value='"+id+"' /> "+id+
"</td><td>"+document.getElementById("name_"+id).value+
"</td><td>"+document.getElementById("price_"+id).value+
"</td><td><input type='text' id='qua_"+id+
"' value='1' disabled='disabled' /></td><td><button>more</button></td></tr>";
to add to table when user click Addbutton
<table id="tbForm1" border="1">
<tbody>
</tbody>
</table>
But I want store it (var table) and assign to other one variable and all row when user click add. How I can ?
Edit
I don't know syntax of JavaScript but if it's PHP, I mean:
$ba .= 'a';
if(click=='add'){
$ba .='b';
}
echo $ba; //outup ab
As Vohuman mentioned use that function to create dynamic row with an Id and use below to add that row to another table.
var x =document.getElementById("tbForm1").getElementsByTagName('tbody');
x.innerHTML = generateRow(id);
Also refer to this to add subsequent rows
How to insert row in HTML table body in javascript?
Related
I've the following PHP code :
//some code
$query = "SELECT * from store_00_transfers";
$result = mysql_query($query);
while($row = mysql_fetch_assoc($result)){
echo "<tr><td align=center width=19%>{$row['item_no']}</td><td align=center><input type='text' value='{$row['qty']}' name='cqty[]' readonly ></td><td align=center><input type='number' min='0' name='nqty[]' onChange='check_not_large(this.value);' value='0'></td></tr>";
}
//rest of code
Now, as you can see there is a function inside onChange. That function is meant to check whether the number inserted by user for new qty should not exceed old qty (I use this method to transfer qty's from one store to another).
Please also note I've assigned a name cqty[] and nqty[] inside input fields.
I have javascript code :
<script>
function check_not_large(res) {
var old = document.getElementsByName("cqty[]");
var type= document.getElementsByName("nqty[]");
for(var i = 0; i < old.length; i++) {
if(type[i].value > old[i].value){
alert('Error : Qty Inserted should be Less than QTY found in Store !');
alert(type[i].value);
alert(old[i].value);
return type[i].value = 0;
}
}
}
</script>
I've used alert in javascript to test if correct values are collected and it seems that it works as needed, but NOT for validating if new qty is more than old qty, it seems that it works only for the first 4 rows then it stucks and starts validating the new qty in any row WITH the first old qty row .. I hope this makes sense to you.
Any alternative or suggestion will be appreciate it.
Thanks Guy
One problem with your code is that everytime you input value onto nqty and on onchange, the function check_not_large function gets called and it not only validating current row nqty and cqty values but also all the previous nqty and cqty row values.If your purpose is to check only if current row nqty value greater than cqty value, a much neater code will be to give some unique id value to each nqty and cqty elements.The code for the same can be optimized as given below.
PHP Code
$query = "SELECT * from store_00_transfers";
$result = mysql_query($query);
while($row = mysql_fetch_assoc($result)){
echo "<tr>
<td align=center width=19%>{$row['item_no']}</td>
<td align=center>
//instead of name attribute you can give an id here and also assuming $row['item_no'] is unique
<input type='text' value='{$row['qty']}' id='cqty{$row['item_no']}' readonly >//assuming item_no is unique
</td>
<td align=center>
//instead of name attribute you can give an id here and also assuming $row['item_no'] is unique
<input type='number' min='0' id="nqty{$row['item_no']}" onChange='check_not_large({$row['item_no']});' value='0'>
</td>
</tr>";
}
Javascript Code
<script>
function check_not_large(item_no) {
var cqtvVal=document.getElementById("cqtv"+item_no).value;
var nqtvVal=document.getElementById("nqtv"+item_no).value;
//checking if typed value is greater than old value
if(nqtvVal>cqtvVal)
{
//write whatever code you want to do like give a warning message or make the nqtv value reset to zero etc
}
}
</script>
I've a PHP file which is a view (so mainly HTML) composed of several tables.
When the user click on one of the button, I want that the variables that are into my cells (and into the correct table) are sent to a Table in my Database.
To do this i'll use AJAX later, but at the moment i've a problem using JS/Jquery.
So I did something like this :
$('.boutton').click(function(){
$(?).find('td input').each(function(){
console.log($(this));
console.log($(this).val());
var iValue = $(this).val();
var sAllId = $(this).attr('id');
var sName = $(this).attr('name')
});
});
My table and buttons are into a div which has as id "table" + the number of the table.
I don't know what to do since I want this to work on every table, and on every button. It has to select only the td input that is into the table where the button was clicked.
My HTML is into a variable $sHtml since everything in this table are made of datas (in my DB) but it should be something like this :
<table id = "domaine-1-south">
<tr>
<th>BlaBla</th> // Several times
</tr>
<tr>
<td>Blabla</td>
<td><input id = "1#1#1#" name="high"></td>
<td><input id = "1#1#1#" name="mid"></td>
<td><input id = "1#1#1#" name="low"></td>
</tr>
<tr>
<td>Blabla</td>
<td><input id = "1#1#2#" name="high"></td>
<td><input id = "1#1#2#" name="mid"></td>
<td><input id = "1#1#2#" name="low"></td>
</tr>
For the id 1#1#1# the last 1 is for the number of the line and the second one is for in which table I'm.
You could use "start with" selector ^= to select all tables that have an id start with table :
$('[id^="table"]').find('td input').each(function(){
But in your OP you want to select the specific table related with the clicked button .boutton, so i guess that you have this button inside the table so you could select the current table using :
$(this).closest('table[id^="table"]').find('td input').each(function(){
Hope this helps.
I want to pass all datas stored in the table in my template. The table is growing by user's choices. My project is about a food ordering system and what i'm trying to do is, when user adds menus to its basket, and make an order, how can i pass the values to my view to save them to my db. I know about forms but my table is not static.. I can't imagine how it will be big.
My add row func:
$(document).ready(function(){
var sum = 0;
$(document).on('click', '.myaddButton', function() {
var $foodname = $(this).closest("tr") // Finds the closest row <tr>
.find(".nr") // Gets a descendent with class="nr"
.text();
var $foodprice = $(this).closest("tr") // Finds the closest row <tr>
.find(".rn") // Gets a descendent with class="nr"
.text();
$('#carttable').prepend("<tr class='danger' id ='myTableRow'><td>"+$foodname+"</td><td class='price'>"+$foodprice+"</td> <td> <button class='deletebutton btn btn-danger' type='button'> <span class='glyphicon glyphicon-trash'></span> </button> </td></tr>");
});
$(document).on('click', '.deletebutton', function() {
$('#myTableRow').remove();
//$('.price').each(function() {
// var $price = $(this);
//console.log($price);
//sum += parseInt($price.context.innerHTML);
//});
//$('#total').html(sum);
//sum = 0;
});
});
</script>
My Table
<table border="1" class="table" id="menutable" name="menutable">
<tr class="danger">
<tbody>
{%for a in list%}
<tr class= {% DoRandom %}>
<td><b> {{a.name}}</b> </td>
<td class="nr">{{a.description}}</td>
<td class="rn"><p>{{a.price}}</p></td>
<td id="addbutton" > <button class="myaddButton btn btn-success" type="button">
<span class="glyphicon glyphicon-plus"></span> </button> </td>
</tr>
{%endfor%}
</tbody>
</table>
If you want to use little bit higher technique of form processing, then you should look at question Making a Django form class with a dynamic number of fields...
Second "simple" solution is to add hidden input values (which will contain food_id and quantity) together with name and price (during prepend), and wrap your table in form. E.g
var $food_id = ... // some how get food id
var $quantity = 1; //1 for now, but you can add increase and decrease functionality
...
// in prepend text
... + "<input type='hidden' name='food-" + $food_id + "' value='" + $quantity + "' >" + ...
And in your template you should add <form> before <table> (and </form> after </table> tags), or use serialize if you are using ajax.
Third solution is to use JS object as cart, and encode it to Json before form submittion. E.g.
//in your javascript global scope
var js_food_cart = {};
....
// then on click
$food_id = ... ;// yes, again you need food id
$quantity = 1; // or something elese
js_food_cart[$food_id] = $quantity;
....
// then somwhere in before submit, code assumes that you have form with my_cart hidden input
$('input[name=my_cart]') = JSON.stringify(js_food_cart);
Then in view you should parse your json value of my_cart input. In template you should add form with hidden field to pass cart value.
This approach more convenient if you will implement ability to increase/decrease quantity of food.
Thanks, i resolved the issue by casting my food objects to json and post by AJAX post.
I have the following html/php table:
<table id="blacklistgrid">
<tr id="Row1">
<td class="space"> </td>
<?php
$query=mysqli_query($mysqli, "SELECT assignment,a_id FROM assignments WHERE groupid=0");
while ($row=mysqli_fetch_array($query)){
echo'<td class="columnname" id="'.$row['a_id'].'" contenteditable="true">'.$row['assignment'].'</td>';
}
?>
<script>
$('.columnname').keyup(function() {
delay(function(){
var text= $('.columnname').text();
var id= $('.columnname').attr('id')
$.ajax({
type:"post",
url:"updateassignment.php",
data:{text:text, id:id},
success:function(data){
console.log('success bro!');
}
});
}, 500 );
});
var delay = (function(){
var timer = 0;
return function(callback, ms){
clearTimeout (timer);
timer = setTimeout(callback, ms);
};
})();
</script>
</tr>
<?php
$query=mysqli_query($mysqli, "SELECT name,memberid_fk FROM groupsort INNER JOIN members ON groupsort.memberid_fk=members.memberid WHERE group_id_fk=0");
while ($row=mysqli_fetch_array($query)){
echo' <tr id="Row2">';
echo' <td>';
echo'<h3>'.$row['name'].'</h3>';
echo'</td>';
$query=mysqli_query($mysqli, "SELECT submitted FROM userassignment WHERE userid=".$row['memberid_fk']." and groupid=0");
$row2=mysqli_fetch_array($query);
if ($row2['submitted']==0){
echo' <td>';
echo' <input type="checkbox" name="red" />';
echo' </td>';
}else if ($row2['submitted']==1) {
echo' <td>';
echo' <input type="checkbox" name="red" checked />';
echo' </td>';
}
echo' </tr>';
}
?>
</table>
Im creating a system to keep track of who submits their homework, so it is in the form of a table. On the left side would be all the names of people (in the class), and the right are individual columns with the names of various assignments.
I am using contenteditable to update the name of the assignment/ and also checkboxes to tick when a student/person submits his assignment.
However, in order to make the tick work, what happens is i need to get the corresponding .columnclass id (which i have assigned as the assignmentid), for me to update the correct field.
The issue now is that the columnclass php is in the front while loop, so im not very sure how to access the column class id from the second php whileloop. QUESTION: Is there a way for php to grab the id of the td(an element) without using javascript?
If user submitted assignment, the submitted row in my table would be 1, so then php would display checked checkboxes. However, as per its mysql query, i need to add the assignment id as well, which can be retrieved from the ID of the corresponding td columnclass id.
The table looks something like this:
Assignment 1 Assignment 2
Name1 CHECKBOX CHECKBOX
Name2 CHECKBOX CHECKBOX
Name3 CHECKBOX CHECKBOX
Name4 CHECKBOX CHECKBOX
So lets say i want to see if name1 submitted assignment1, then in my mysql table, i need to feed it both the userid AND the corresponding assignment id, therefore to retrieve the assignment id, i need to grab the id of the "assignment 1" .columnclass element's id (which i stored the value of assignmentid) I feel that this is a hack, is there a better way to do this?
Note i removed the add column/row code in the code snippet above to increase simplicity.
To make it even simpler to understand the table code above, the table is created like this:
(row 1) emptytd1 td2(assignment)..
(row 2) td1(name) td2(checkbox)..
.
.
To determine if td2 should be checked, i need to query the database, and to do that, since there are multiple users and multiple assignments, i need the name and the assignment, the name is easy to get since it is within the query, but the assignment is in the previous php while loop.
Looks like, when you get to listing out the users in your table, you're not looping over the existing assignments. What you have only writes to the first assignment column, regardless of what assignment the user submitted.
So, below are a few tweaks of your existing code. First I added two lines to your assignments header row, marked with comments. The first creates an assignments array (for later use), and the second loads that array with the existing assignments.
Then, when looping over the users, for each user I added a loop over the existing assignments array. This accomplishes two things, 1) it puts aligns the assignments to the appropriate column, and 2) it gives you the assignment id you need to check if the user submitted the assignment. (I also used prepared statements for added security.)
NOTE: I'm guessing that your "userassignment" table has a field named "a_id" that gets set along with "userid" when a user submits an assignment.
<table id="blacklistgrid">
<tr id="Row1">
<td class="space"> </td>
<?php
$query=mysqli_query($mysqli, "SELECT assignment,a_id FROM assignments WHERE groupid=0");
$assignments = array(); // create empty assignments array
while ($row=mysqli_fetch_array($query)){
echo'<td class="columnname" id="'.$row['a_id'].'" contenteditable="true">'.$row['assignment'].'</td>';
$assignments[$row['a_id']] = $row['assignment']; // add assignment to array
}
?>
<script>
$('.columnname').keyup(function() {
delay(function(){
var text= $('.columnname').text();
var id= $('.columnname').attr('id')
$.ajax({
type:"post",
url:"updateassignment.php",
data:{text:text, id:id},
success:function(data){
console.log('success bro!');
}
});
}, 500 );
});
var delay = (function(){
var timer = 0;
return function(callback, ms){
clearTimeout (timer);
timer = setTimeout(callback, ms);
};
})();
</script>
</tr>
<?php
$query=mysqli_query($mysqli, "SELECT name,memberid_fk FROM groupsort INNER JOIN members ON groupsort.memberid_fk=members.memberid WHERE group_id_fk=0");
while ($row=mysqli_fetch_array($query)){
echo' <tr id="Row2">';
echo' <td>';
echo'<h3>'.$row['name'].'</h3>';
echo'</td>';
// LOOP OVER ASSIGNMENTS ARRAY
foreach ( $assignments as $a_id => $assignment ) {
$query2=mysqli_prepare($mysqli, "SELECT submitted FROM userassignment WHERE userid=? and groupid=0 and a_id=?"); // added assignment id condition
mysqli_stmt_bind_param($query2, "ii", $row['memberid_fk'], $a_id);
mysqli_stmt_execute($query2);
mysqli_stmt_bind_result($query2, $submitted);
mysqli_stmt_fetch($query2);
$checked = ( $submitted )? 'checked': '';
echo" <td> <input type=\"checkbox\" name=\"red\" $checked /> </td>";
mysqli_stmt_close($query2);
} // end assignments array loop
echo' </tr>';
}
?>
</table>
I'm working on an invoice system. By default it loads with 1 row to input items. If a administrator wants to add additional items they may click a link which executes a JavaScript to add additional rows. This is working great for me.
I submit the form using POST method to the same page. If a user added additional rows using the JavaScript, it loads with the previous amount of rows as when the page was submitted. To do this I used PHP $table_rowcount = count( $_POST["item_details"] );. Just FYI, the {$table_rowcount} isn't a syntax error as I'm using a template engine.
Everything works great to this point. Administrators can add additional rows to input data and when the page is submitted to itself it loads those number of rows. Perfect. However this is where the problem comes in.
What I need to do is use a method of sticky forms so if there is an error, the page will reload (as it currently does) with variables assigned to each inputs value="" so the administrator wont have to re-enter all the details.
The problem is I do not know how to do this with a combination of JavaScript and PHP. I need to some how get the current number of the row using the for() loop in JavaScript and then use that number in a PHP variable as seen in the tbody of the HTML below for the default 1st row.
Basically if it is the 3rd row and the for() loop will show it as var i = 2 (since array starts at 0), how can I use JavaScript to help me call the PHP variable {$item.2.details}.
I'm assuming I need to use AJAX for this? However I do not know AJAX. I'm hoping someone could assist me with this so myself and others can learn how this is properly done.
Question simply put
How can I use a JavaScript variable to select a PHP array in a HTML file?
JavaScript:
<script type="text/javascript">
window.onload = function loadRows() {
for( i = 1; i < {$table_rowcount}; i++ ) {
// Set table id.
var table = document.getElementById("invoice_items");
// Count rows.
var rowCount = table.rows.length;
// Row to insert into table.
var row = table.insertRow(rowCount);
// Cells to insert into row.
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
// Current Row.
var rowNumber = rowCount + 1;
// Data in cells.
cell1.innerHTML = "<textarea name=\"item_details[]\"></textarea>";
cell2.innerHTML = "<input type=\"text\" name=\"item_quantity[]\" value=\"\" />";
cell3.innerHTML = "<input type=\"text\" name=\"item_price[]\" value=\"\" />";
}
}
</script>
HTML:
<form method="post" action="index.php?do=invoices_add">
<label class="label">
<div class="left">
Invoice Items
</div>
<table id="invoice_items" cellpadding="0" cellspacing="0" border="0">
<thead>
<tr>
<td>
Item Details
</td>
<td>
Quantity
</td>
<td>
Price
</td>
</tr>
</thead>
<tbody>
<tr>
<td>
<textarea name="item_details[]">{$item.0.details}</textarea>
</td>
<td>
<input type="text" name="item_quantity[]" value="{$item.0.quantity}" />
</td>
<td>
<input type="text" name="item_price[]" value="{$item.0.price}" />
</td>
</tr>
</tbody>
</table>
+ Add Item
</label>
<br/>
<label class="label">
<input type="submit" value="submit" name="submit" />
</label>
</form>
Just to make sure I understand correctly: You have users who enter new rows, and if there is an error, their newly entered rows are lost, along with the information they typed. Based on that:
My first instinct is to post the form via AJAX, but if you want to go the PHP route, I would recommend researching session based flash messages. You can use session data to send back the values which have already been input, along with additional error messages. I have previously set flash data as one object with property names such as "errors". "errors" would be an array of error messages, but you can also set a property called "additionalItem" and add the newly created items by the user. Then add these to your row iteration in the PHP, avoiding the necessity of using JavaScript to build the rows.
$flashData = Array("additionalItem" => Array());
for ($_PARAMS["addedRows"] as $row) {
$flashData["additionalItem"] []= Array(
"rowDetails" => $row['details'],
"rowQuantity" => $row['quantity'],
"rowPrice" => $row['price']
)
}
I would also recommend client side validation where possible. However, I also understand other non-client-side errors can arise.
If you have to do it in JavaScript then I think your best option here is to expose the PHP array you want to iterate over and store it as a JavaScript variable (so either way you will probably need to set flash data).
<script type="text/javascript">
// I renamed item to items as I am assuming you have an array.
// This would preferably be an array of items from the server.
var items = {$items},
table = document.getElementById("invoice_items");
window.onload = function loadRows() {
for (i = 1; i < items.length; i++) {
var rowCount = table.rows.length,
row = table.insertRow(rowCount),
cell1 = row.insertCell(0),
cell2 = row.insertCell(1),
cell3 = row.insertCell(2),
rowNumber = rowCount + 1;
cell1.innerHTML = "<textarea name='item_details[]'>" +
items[i].details + "</textarea>";
cell2.innerHTML = "<input type='text' name='item_quantity[]'
value='' />";
cell3.innerHTML = "<input type='text' name='item_price[]'
value='' />";
}
}
</script>
I hope this helps and that I did not misunderstand the question :)