Javascript - calculating the remaining between two related fields - javascript

First of all, I would like to calculate the remaining QTY (quantity) between two fields in a form; in other words I have the actual QTY input text field as a read-only where its value is obtained from mysql table AND there is the user QTY input text field is taken from the user input. All I want is to decrement the actual QTY based on what the user input in the user QTY.
I have the following code as follows :
$query2 = "SELECT * from store_00";
$result2 = mysql_query($query2);
$n = array();
while($row2 = mysql_fetch_assoc($result2)){
echo "<td align=center>".$row2['item_no']."</td><td align=center>";
?>
<input type="text" id="fname" value="<?php echo $row2['qty'] ?>" readonly="readonly"/>
<?php
echo "</td>";
for($i=0;$i<$num;$i++){
echo "<td align=center>"; ?><input autofocus="autofocus" onchange="myFunction(this.value);" type="text" name="n[]" value=""/><?php echo "</td>";
}
echo "</tr>";
}
And the Javascript code :
function myFunction(v)
{
var x=document.getElementById("fname");
x.value = x.value - v;
}
The above will output in the actual QTY correctly for the first time, but when user changes the value back to 0 , it will decrements from the new actual QTY value which gives a false remaining...So there must be a way to have a temporary actual QTY value saved somewhere.
Anyways I know the code looks awful, I'm still new to JS and not sure how to just create a simple relation and remaining calculation between two fields.

As you don't use jQuery and your question is about javascript, i've changed some things to do what you want easily. Also, the id should be unique while classes don't need to be unique. As you have ids with the same values that creates a problem, also as you stated, you don't store your original value, and this is your main problem. There are many methods for this but i prefer this as it's easy to understand i guess.
$n = array();
echo "<table>";
while($row2 = mysql_fetch_assoc($result2)){
echo "<tr class='inputs'>";
echo "<td align=center> ".$row2['item_no']." </td><td align=center>";
echo "<input class='original' type='text' id='c".$row2['item_no']."' value='".$row2['qty']."' readonly='readonly'/>";
echo "</td>";
for($i=0;$i<$num;$i++){
echo "<td align=center>";
echo "<input class='d".$row2['item_no']."' data-goto='c".$row2['item_no']."' data-original = '".$row2['qty']."' autofocus='autofocus' onchange='myFunction(this);' type='text' name='n[]' value='0'/>";
echo "</td>";
}
echo "</tr>";
}
echo "</table>";
With the html5, you can define custom tags with the data- prefix, and you can reach them with getAttribute method for that object.
<script>
function myFunction(v){
var minus = 0;
var mutualInputs = document.getElementsByClassName(v.className);
for (var i = 0; i < mutualInputs.length; ++i) {
var item = mutualInputs[i];
minus = minus + parseInt(item.value);
}
var original = v.getAttribute('data-original');
var x = document.getElementById(v.getAttribute('data-goto'));
x.value = original - minus;
}
</script>
ps: your item_no's must be unique in this example.

Related

Causing Uncaught type (reading 'value') error when I click submit

I made the zone with checkbox list if I type in the value and that entered value is in Database. But when I click submit, it shows Uncaught TypeError: Cannot read properties of undefined (reading 'value'). I named both name and id as chkzone. Error is causing in var chkzone = document.translot.chkzone.value; line.
while ($row = mysqli_fetch_assoc($result1)) {
$field1name = $row["lotid"];
$field2name = $row["product"];
$field3name = $row["ewsflow"];
$field4name = $row["zone"];
$key = $field1name + ":" + $field2name + ":" + $field3name;
if (!in_array($key, $arr)){
echo "<tr>";
echo "<th >Lot ID:</th>";
echo "<td >$field1name</td>";
echo "</tr>";
echo "<tr>";
echo "<th>Product:</th>";
echo "<td>$field2name</td>";
echo "</tr>";
echo "<tr>";
echo "<th>EWSFLOW: </th>";
echo "<td>$field3name</td>";
echo "</tr>";
array_push($arr, $key);
}
echo "<tr>";
echo "<th>Zone - $field4name</th>";
echo "<td><input type=\"checkbox\" name=\"chkzone\" id=\"chkzone\" value=\"$zone\"></td>";
//echo "<td>$field4name</td>";
echo "</tr>";
Below is in JavaScript.
var chkzone = document.translot.chkzone.value;
if (chkzone == null || chkzone == ""){
alert("Please choose zone to disable for Correlationwafer.");
return false;
}
{
document.getElementById("result").innerHTML = SynReqData(reqHttp2,'correlationwafer_result.php?productlotid=' + productlotid + '&chkzone' + chkzone);
return false;
}
The reason you get that error is because document.translot.chkzone is undefined. In other words, if you have an element like that in your webpage this must not be the right path to access it.
It's a little challenging to know exactly why that is without seeing your full web page, but given what you're echoing in PHP you might be able to change this:
var chkzone = document.translot.chkzone.value;
into this
var chkzone = document.querySelector('#chkzone').value;
which should work because you've given your input an id of chkzone. If this doesn't work, then please share with us when your javascript code is running, as your issue might be that it's running somewhere before this input element is inserted to the DOM of your webpage.
edit: Also unrelated to your question, but I believe you're missing an = sign here: '&chkzone' + chkzone); -> '&chkzone=' + chkzone);

Can i pass array to an HTML? Creating a dynamic html table with php/javascript

I have created a table with 3 columns and rows with the size of an array pulled from the database. I have got the value but I want to create a button inside the cells with the name from pname and when you click that button it will take you to the value of plink. I tried using <input type="button" value=" " onclick="window.open( )", but it doesn't seem to pass the arrays. I am sure there is an easier/ better way to do it with JavaScript, but I am not familiar with JavaScript. Please help me out. Here is my code.
I want the format 3 columns and infinite rows(based on the data).
<!DOCTYPE html>
$pname = array();
$plink = array();
$results = $wpdb->get_results("SELECT name, link FROM `wptable`);
if(!empty($results)) {
foreach($results as $row){
$pname[] = $row->name;
$plink[] = $row->link;
}
}
$num = 0;
echo "<table class='table'>";
echo "<tbody>";
echo "<br><br>";
$quant_row = count($pname)/3;
$quant_col = 3;
for ($count_row = 0; $count_row < $quant_row; $count_row++)
{
echo "<tr>";
for ($count_col = 0; $count_col < $quant_col; $count_col++)
{
echo "<td>";
echo $plink[$num];
echo "</td>";
$num++;
}
echo "</tr>";
}
echo "</tbody>";
echo "</table>";
?>
You just need to echo a button inside an anchor:
echo '<button type="button">' . $pname[$num] . '</button>';
try this.
echo "<td>";
echo "<button onclick=\"Document.getElementById('link$num').display=state$num? 'none' :'block';state$num=!state$num; \">". $pname[$num] ."</button><div id='link$num'>". $plink[$num]."<div>";
echo "";
when you click on $pname , you show the $plink. reclick and hide the content

Alerting only 1st Product Code from table?

So, I have a table emitting data from database table.
//Display the simplex table
echo "<div id='simptable'>";
$sqlGet = "SELECT * FROM simplex_list";
//Grab data from database
$sqlSimplex = mysqli_query($connect , $sqlGet)or die("Error retrieving data!");
//Loop to display all records on webpage in a table
echo "<table>";
echo "<tr><th>Product Code</th><th>Description</th><th>Quantity</th></tr>";
while ($row = mysqli_fetch_array($sqlSimplex , MYSQLI_ASSOC)) {
echo "<tr><td>";
echo "<input type='text' id='sim' value='".$row['s_code']."' readonly>";
echo "</td><td>";
echo $row['description'];
echo "</td>";
echo "<input type='hidden' id='com' name='complexcode' value='$newProductID'>";
echo "<td>";
echo "<input type='text' size='7' id='userqty'>";
echo "</td><td>";
echo "<input type='button' onclick='addthis()' value='Add!'>";
echo "</td></tr>";
}
echo "</table>";
echo "</div>";
And I try to alert the 'Product Code' here when the user clicks 'Add' button....
function addthis() {
var scode = $('#sim').val();
alert(scode);
}
The problem is it only alerts the first Product Code in the table. That from row 1.
Example:
Product code Name More
123 Toy 'Add'
321 Food 'Add'
555 Pen 'Add'
So if I click on 'Add' for food or pen it will still alert 123..
Any ideas?
ID must be unique.
You can do something like following. Add parameter in onclick function. Which will be ID of row.
echo "<input type='button' onclick='addthis(".$row['s_code'].")' value='Add!'>";
^^^
Parameter added in above code. Now javascript function can be:
function addthis(scope) {
alert(scode);
}
As I stated in comments, the ID of your input must be unique. You're currently assigning 'sim' as the ID to every input in your loop over the data results.
One approach to fix this:
$i = 0;
echo "<input type='text' id='sim" . $i ."' value='".$row['s_code']."' readonly>";
And then add a unqiue id to your button using the same incrementor:
echo "<input type='button' id='btn" . $i . "' value='Add!'>";
$i++; //then increment
Notice that the button and the input have the same number at the end of their id. You can use this to parse the id of the button and use it to find the input.
Tie the click event with:
$(document).on('click', '[id^="btn"]', function() {
var id = $(this).attr('id').split('btn')[1];
var val = $('#sim' + id).val();
console.log(val);
//do other stuff
});
UPDATE: JSFiddle

Keeping checkboxes checked with fetch array

Here is the code which I have on the site, it retrieves each season and then numbers of home wins, win percentage and win lsp which is all fine and it creates a new line in the table for each season.
I then have two columns which filter out the data (Min & Max) which are radio buttons and these work fine, they stay checked after I submit and the values work fine.
The one that I am having problems with is the 'Checkbox' which I need to keep checked after the form is submitted, it only keeps one of the checkboxes checked after I submit it.
<form action='' method='post'>
<?php
echo "<table id='stats' width='100%' border='1' cellspacing='1' cellpadding='1'>
while($row = mysql_fetch_array($resultsseason, MYSQL_ASSOC)) {
echo "<tr bgcolor='#FFFFCC'>";
echo "<td align='center'><input type='radio' class ='radio-button' name='seasonmin' value='".$row['season']."'" . ((#$_POST['seasonmin'] == $row['season'])?'checked="checked"':"") . "/></td>";
echo "<td align='center'><input type='radio' class ='radio-button' name='seasonmax' value='".$row['season']."'" . ((#$_POST['seasonmax'] == $row['season'])?'checked="checked"':"") . "/></td>";
**echo "<td align='center'><input type='checkbox' name='seasonexc' value='".$row['season']."'/></td>";**
echo "<td align='center'>" . $row['season'] . "</td>";
echo "<td align='center'>" . $row['countp'] . "</td>";
echo "<td align='center'>$profitwb1<font color='$profitw'>" . $row['counth'] . "</font>$profitwb2</td>";
echo "<td align='center'>$profitwb1<font color='$profitw'>" . $row['WinPer'] . "%</font>$profitwb2</td>";
echo "<td align='center'>$profitwb1<font color='$profitw'>" . $row['WinLSP'] . "</font>$profitwb2</td>";
echo "</tr>";
}
echo "</table>";
?>
<hr><br>
<input type="submit" value="Update" >
<script type="text/javascript">
var allRadios = document.getElementsByName('seasonmin');
var booRadio;
var x = 0;
for(x = 0; x < allRadios.length; x++){
allRadios[x].onclick = function() {
if(booRadio == this){
this.checked = false;
booRadio = null;
}else{
booRadio = this;
}
};
}
</script>
<script type="text/javascript">
var allRadios = document.getElementsByName('seasonmax');
var booRadio;
var x = 0;
for(x = 0; x < allRadios.length; x++){
allRadios[x].onclick = function() {
if(booRadio == this){
this.checked = false;
booRadio = null;
}else{
booRadio = this;
}
};
}
</script>
I have searched and read plenty of posts on keeping them checked but I cannot seem to figure it out! The line which I need help with is..
echo "<td align='center'><input type='checkbox' name='seasonexc' value='".$row['season']."'/></td>";
and how to keep ALL which are checked, checked after I hit submit!
Thank You in advance!
Checkboxes differ from radio buttons in that they're not grouped. Whereas with radio buttons you can only have one of those sharing the name attribute checked, with checkboxes you must use different names.
In your case you're printing a bunch of checkboxes with the same name, which results in just one of them being submitted. A good convention is to use an array-type name, which in your case would be seasonexc[]. If you're keeping track of indices, change that to seasonexc[".$index."].
Also, I noticed that with your problematic line the checked attribute was missing altogether, thus preventing any of them being checked.
I have found that a simple...
if (isset($_POST['seasonexc']) && is_array($_POST['seasonexc']) && in_array($row['season'], $_POST['seasonexc'])) { $checked = "checked='checked'"; } else { $checked = ""; }
and then calling $checked has solved the problem! Always the way of trying to overthink it!

Updating value of textbox getting value from first text box only

I have cart page in which text box is present for updating quantity, I'm using jquery to listen to the click event & get the values of productid & the textbox. Productid I'm getting fine but value of textbox always is the value in first textbox.
Here is the code of cart file
echo "<tr>";
echo "<th><img src=".$row["image_location"]."></th>";
echo "<th>".$row["product_name"]."</th>";
echo "<th><input type='text' id='quantity' name='quantity' required='required' autocomplete='off' value=".$row["quantity"].">";
echo "&nbsp";
echo $row["type"]."</th>";
echo "<th>".$row["price"]."</th>";
echo "<th>"."₹ ".$subtotal."</th>";
echo "<th><div class='buttoncircle' id='".$row["productid"]."'>Update</div></th>";
echo "<th><a href='removefromcart.php?productid={$row["productid"]}' class='buttoncircle' style='margin-left:-65px'>Remove</a></th>";
echo "</tr>";
Here is the code for javascript.
<script>
$('.buttoncircle').live('click',function() {
var productid = $(this).attr('id');
var quantity = $('#quantity').val();
window.open('db_changequantity.php?quantity='+quantity+'&productid='+productid,'_self');
});
Can anyone help calling the value of particular textbox & not from the first one only?
Added dynamic id for the quantity filed - id='quantity_".$row["productid"]."' and mapped the same in javascript var quantity = $('#quantity_'+productid).val();.
In PHP
echo "<tr>";
echo "<th><img src=".$row["image_location"]."></th>";
echo "<th>".$row["product_name"]."</th>";
echo "<th><input type='text' id='quantity_".$row["productid"]."' name='quantity' required='required' autocomplete='off' value=".$row["quantity"].">";
echo "&nbsp";
echo $row["type"]."</th>";
echo "<th>".$row["price"]."</th>";
echo "<th>"."₹ ".$subtotal."</th>";
echo "<th><div class='buttoncircle' id='".$row["productid"]."'>Update</div></th>";
echo "<th><a href='removefromcart.php?productid={$row["productid"]}' class='buttoncircle' style='margin-left:-65px'>Remove</a></th>";
echo "</tr>";
Javascript:
$('.buttoncircle').live('click',function() {
var productid = $(this).attr('id');
var quantity = $('#quantity_'+productid).val();
window.open('db_changequantity.php?quantity='+quantity+'&productid='+productid,'_self');
});

Categories