Javascript getElementsByName not working in PHP loop - javascript

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>

Related

JavaScript how to add data to a variable

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?

How do I attach checkboxes to a submit

I have unknown amount of checkbox inputs on a page created based on rows in an sql database.
The checkboxes look like:
<input type="checkbox" class="deletefunc" value="<? echo $mid; ?>">
The checkboxes are intended, when checked and submitted, to delete a row from the database based on the value of $mid
The checkboxes could be either loose (not contained in any forms), or each could be contained in its own form (without a submit button). There is no way however to contain all the checkboxes in one form.
The reason is it's displayed in a loop with output like this:
<tr>
<td><input type="checkbox" class="deletefunc" value="<? echo $mid; ?>"></td>
<td><input type="checkbox" class="star" value="1"> <!-- jquery/ajax onclick function --></td>
<td><a href></td>
<td><form name....><input type="submit" value="something"></form></td>
<tr>
So what I need help understanding is, how to gather all the checkboxes based on classname, and attach them to a submit button....
And further, how would I write the loop function so it knows how many deletes to perform? What I mean is, how would I write a loop that would get the values from an unknown amount of inputs. Normally I know how many inputs there are and what the names are so its a matter of assigning a variable for each input.... I've never done this with an unknown amount of inputs.
I would do it like this:
HTML:
<input type="checkbox" class="deletefunc" value="<? echo $mid; ?>">
<button id="delete-them">Delete Them</button>
JS:
$(function() {
$('#delete-them').on('click', function() {
var data = $('.deletefunc').attr('name', 'delete[]').serialize();
$.ajax('delete-them.php', {
method: 'POST',
data: data,
success: function() {
alert('deleted!');
}
});
});
});
PHP:
<?php
$ids = $_POST['delete'];
$params = array_fill(0, count($ids), "?");
$sql = "DELETE FROM some_table WHERE id IN (" . implode(",", $params) . ")";
//DELETE FROM some_table WHERE id IN(?,?,?,?);
$pdo = new PDO('mysql:host=localhost;dbname=mydb', 'user', 'pass');
$stmt = $pdo->prepare($sql);
$stmt->execute($ids);
?>
So we basically listen for a click on our button, when it happens, we set the name (with [] at the end so it becomes an array) for all of the items with the class we care about, so that when we serialize those items we know how to reference it in our PHP.
We then POST that data over to the server, where we read the array we just sent, see how many there are, and then create a query to delete those items.

PHP grab corresponding column id

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>

Clear input field value after javascript alert

I have a dynamic field that get value from database, and I want to check one of the field value if it was greater from the old value or not. If it does greater, i have to give an alert and reset field value back to ''
i want to do it without using document.GetElementById because the field was looped by foreach, I'm tryin to work with document.GetElementByName but got no where. here's my code
<?php foreach ($items->result_array() as $row){ ?>
<tr>
<td><p><?php echo $row['nmbr']; ?> </p>
<p><?php echo $row['urai']; ?><p> </td>
<td><?php echo $row['jml']?> </td>
<td><div class="oldprice"><?php echo $row['oldprice']?></div></td>
<td><input id="pnwrn" class="pnwrn" type="text" name="pnwrn[]" value="" data-harga="<?php echo $row['jml']?>" data-jumlah="<?php echo $row['oldprice']?>"/></td>
<td><div class="output"></div></td>
</tr>
<?php } ?>
and this is my javascript :
<script type="text/javascript">
$('.pnwrn').on('change', function () {
var twrn = $(this).val();
var price = parseInt($(this).data('harga'));
var jmlh = parseInt($(this).data('jumlah'));
if (twrn <= jmlh){
$(this).parents('tr').find('.output').html(twrn*price);
}
else {
alert("Price can not be greater from old price");
cleartext();
}
});
function clearInputs() {
document.getElementByName("pnwrn").value = "";
}
</script>
can someone help me?
You are not supposed to have multiple elements with the same id. Instead, try this:
<td><input id="pnwrn<?php echo $row['some_id_field_that_you_have']; ?>" class="pnwrn" type="text" name="pnwrn[<?php echo $row['some_id_field_that_you_have']; ?>]" value="" data-harga="<?php echo $row['jml']?>" data-jumlah="<?php echo $row['oldprice']?>"/></td>
You can also attach the matching ID on the <tr>, or to other elements, which makes it trivial to find the appropriate elements.
Unfortunately, with names like urai, harga, jumlah and pnwrn, it is extremely hard to pinpoint what exactly you're trying to do, thus just vague hints.
But - if you're trying to clear the very field you're checking, you already have it, so no lookup needs to be done. Just do clearInput(this).
Try this to loop through all the inputs and match on the class you want:
$("input").each(function (i) {
if ($(this).prop("class") === "pnwrn") {
$(this).val('');
}
});

Javascript Variable in PHP Array Variable?

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 :)

Categories

Resources