monitor and update variable number of fields in php form - php

I have an inventory form that pulls a variable number of rows of items from a database and creates a table/list of them, with input text boxes for quantity of cases( of 12) and individual items, and the script updates the total box with the sum of those two. I have it working if I put discrete sections of code in for each row, and have tried many while/for loops and the problem I think is the function is inside the loop and stops it from working. I looked at posts using .each() , but do not see any example that works with my setup. I went and answered a couple simple questions on here for others before posting this question, hoping to please the code gods ;-)
<form>
<div class="ex3">
<div class="headrow">
<div class="column">Batch</div>
<div class="column">Name</div>
<div class="column">UPC</div>
<div class="column">Cases</div>
<div class="column">Bottles</div>
<div class="column">Counted</div>
</div>
<?php
// grab all the pertinant entries from the database and create a row of entries for each one
$sql="SELECT BatchNum, BatchName, UPC FROM Batches WHERE CurrentBatch=1 AND UPC <> '' ORDER by BatchNum DESC";
$result = $mysqli->query($sql);
$numrows = $result->num_rows;
if ($result->num_rows > 0) {
$row_cnt = 0;
while ($row = $result->fetch_assoc()) {
echo '<div class=row>';
echo '<div class=column>'.$row['BatchNum'].'</div>';
echo '<div class=column>'.$row['BatchName'].'</div>';
echo '<div class=column>'.$row['UPC'].'</div>';
echo '<div class=column> <label for="CaseCount"></label><input type="text" inputmode="numeric" pattern="^\d{1,3}$" size="4" class="form-control" id="CaseCount'.$row_cnt.'" name="CaseCount'.$row_cnt.'" value="" ></div>';
echo '<div class=column> <label for="BottleCount"></label><input type="text" inputmode="numeric" pattern="^\d{1,3}$" size="4" class="form-control" id="BottleCount'.$row_cnt.'" name="BottleCount'.$row_cnt.'" value=""></div>';
echo '<div class=column> <label for="Counted"></label><input type="text" inputmode="numeric" pattern="^\d{1,8}$" size="8" class="form-control" id="Counted'.$row_cnt.'" name="Counted'.$row_cnt.'" value="" required></div>';
$row_cnt += 1;
echo "</div>";
}
}
?>
</div>
</li>
</ul>
</div>
</form>
<script>
// monitor the case and bottle count fields and update the counted field.
$(document).ready(function() {
$('#CaseCount0, #BottleCount0').on('input', function() {
var Counted0 = 0;
var value1 = $('#CaseCount0').val();
var value2 = $('#BottleCount0').val();
var Counted0 = (value1 * 12) + (value2 * 1);
$('#Counted0').val(Counted0);
});
$('#CaseCount1, #BottleCount1').on('input', function() {
var Counted1 = 0;
var value1 = $('#CaseCount1').val();
var value2 = $('#BottleCount1').val();
var Counted1 = (value1 * 12) + (value2 * 1);
$('#Counted1').val(Counted1);
});
$('#CaseCount2, #BottleCount2').on('input', function() {
var Counted2 = 0;
var value1 = $('#CaseCount2').val();
var value2 = $('#BottleCount2').val();
var Counted2 = (value1 * 12) + (value2 * 1);
$('#Counted2').val(Counted2);
});
// might be 20-30 of these lines
});
</script>
here is a script section I have tried, but could not get to work, I do not think it is good practice for the function to be inside the loop:
var numrows = <?php echo $numrows ?>-1;
var i;
$(document).ready(function() {
for(var i = 0; i <= numrows; i++) {
$("#CaseCount"+i).on('input', function() {
this["Counted"+i] = 0;
var value1 = $("#CaseCount" + i).val();
var value2 = $("#BottleCount" + i).val();
$("#Counted"+i).val((value1 * 12)+(value2 * 1));
});
}
});

Related

Autocomplete search box from MySQL that displays multiple columns

I've been trying to make an autocomplete search box from a MySQL database that displays multiple columns of data when searching.(ie. Searching for an item #, at it displays the item number, manufacturer, and price)
Below is what I have currently done, which displays everything in one line separated by spaces. I would like to have a way to change the style for each column or make each result display in multiple lines if possible.
I'm a complete noob at this so any advice/resources would be awesome!
//ajax-db-search.php
<?php
require_once "db.php";
if (isset($_GET['term'])) {
$query = "SELECT DISTINCT MFG_Item_ID, MFG_Name, Price FROM H_Item_Master WHERE MFG_Item_ID LIKE '{$_GET['term']}%' LIMIT 5";
$result = mysqli_query($conn, $query);
if (mysqli_num_rows($result) > 0) {
while ($user = mysqli_fetch_array($result)) {
$res[] = $user['MFG_Item_ID'] . " " . $user['MFG_Name'] . " " . $user['Price'];
}
} else {
$res = array();
}
//return json res
echo json_encode($res);
}
?>
//in my index.php
<!-- Topbar Search Catalog -->
<form
class="d-none d-sm-inline-block form-inline mr-auto ml-md-3 my-2 my-md-0 mw-100 navbar-search">
<div class="input-group">
<input type="text" name="term" id="term" placeholder="Search Catalog" class="form-control"
aria-label="Search" aria-describedby="basic-addon2">
<div class="input-group-append">
<button class="btn btn-primary" id="benchbutton" type="Submit">
<i class="fas fa-search fa-sm"></i>
</button>
</div>
</div>
</form>
<script type="text/javascript">
$(function() {
$( "#term" ).autocomplete({
source: 'ajax-db-search.php',
});
});
</script>
You can override the default autocomplete style this way, so you can use html br tags and your own css stylesheet :
<script type="text/javascript">
$(function() {
$( "#term" ).autocomplete({
source: 'ajax-db-search.php',
select: function(event, ui) {
$("#term").val(ui.item.name);
return false;
}
})
.autocomplete("instance")._renderItem = function(ul, item) {
return $("<li class='each'>")
.append("<div class='item'><span class='upc'>" +
item.upc + "</span><br><span class='name'>" +
item.name + "</span><br><span class='price'>" +
item.price + "</span><br></div>")
.appendTo(ul);
};
});
</script>
Using the span's classes, you have full control on any attribute (upc, name and price) in CSS :
<style>
.each .item .upc{
font-style:italic;
color:blue;
}
</style>
Here is the final result :
Using this dataset :
PS : Here is how to use prepared statement to select and fetch datas from database :
if(isset($_GET['term']))
{
$term = '%' . $_GET['term'] . '%';
$sql = "SELECT * FROM items WHERE CONCAT(upc, name) LIKE ? LIMIT 5";
$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $term);
$stmt->execute();
$result = $stmt->get_result();
$items = [];
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$items[] = $row;
}
}
$conn->close();
echo json_encode($items);
}

How to iterate associative multidimensional array in Javascript/JSON/AJAX with PHP

My database results are multidimensional array.
Here is my code in php file.
$course_detail = array();
while($row=mysqli_fetch_assoc($result))
{
//$course_detail[] = $row;
$course_detail[ strtoupper($row['course_name'][0]) ][] = array(
'course_name' => $row['course_name'],
'duration' => $row['duration'],
'c_desc' => $row['c_desc']
);
}
echo json_encode($course_detail);
And here is my Ajax/Javascript/JSON code.
<script type="text/javascript" >
function fetch(val) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if(xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("response").innerHTML = "";
var j = JSON.parse(xhttp.responseText);
for (var i = 0; i < j.length; i++)
{
document.getElementById("response").innerHTML = j[i]['name'] + ' ' + j[i]['duration']+ ' ' + j[i]['c_desc'] ;
}
}
}
xhttp.open('get', 'stream-process.php?sname='+val, true);
xhttp.send();
}
This javascript function is called from submit button with ID of hidden element which is generated dynamically.
Here is the code:
<form action="" method="get">
<?php
$db_manager = new db_manager();
$db_manager->DBLogin();
$sql = "select * from streams";
$result=mysqli_query($db_manager->connection,$sql);
$counter = 1;
while($row=mysqli_fetch_array($result))
{ ?>
<input type="hidden" id="stream_name<?php echo $counter ?>" class="stream" name="sname" value="<?php echo $row["scode"]; ?>">
<li class="list-group-item"><input class="form-control" onclick="fetch(document.getElementById('stream_name<?php echo $counter;?>').value)" type="button" id="submit" value="<?php echo $row["name"]; ?>"/></li>
<?php
$counter++;
}
?>
</form>
</div>
<div id="response" class="stream-detail col-sm-8">
hey there......
</div>
when i click on any button, nothing is displaying. It worked correct with Simple multidimensional array. but i want in Associative Multidimensional Array. So that i can treat each field of each row differently.
Thanks in advance.

Is there a limit on the amount of JavaScript Files on your head?

I'm asking because every time I use a second javascript my code gets buggy. At first the JS file was one and I was trying to make it work for both the select tags I'm working with. I wasn't able to implement it. Called it quiets and copied it but renamed everything to avoid any conflicts in the name. But my errors keep on happening. Maybe there's something wrong with my code or?
html Head
<head>
<title>Packages</title>
<link rel="icon" type="image/ico" href="../favicon.ico"/>
<link rel="stylesheet" type="text/css" href="../style/style_p.css"/>
<script type="text/javascript" src="../style/add_fields.js"></script>
<script type="text/javascript" src="../style/addMoreFields.js"></script>
<h1><img src="../images/Logo.png" alt="Logo"></h1>
</head>
JS 1
var instance = 0;
function moreFields(parentHome, cloneHome) {
// Check if there isn't more than 3 fields
if(instance != 3) {
instance++;
// Create a child
var TempClone = document.getElementById(parentHome).cloneNode(true);
// remove templet clone's id to avoid future confusion
TempClone.id = "";
TempClone.style.display = 'block';
/* Get the cloned templet's
* Children. Here we will make
* only the ones who have a name
* unique.
*/
var cloneC = TempClone.childNodes;
for(var i = 0; i < cloneC.length; i++) {
var ChildName = cloneC[i].name;
if(ChildName)
cloneC[i].name = ChildName + instance;
}
// Locate clone's home
var insertHere = document.getElementById(cloneHome);
// Place clone in home
insertHere.parentNode.insertBefore(TempClone,insertHere);
}
}
window.onload = function() {
moreFields('SnackBox', 'SnackPlate');
}
JS2
var counter = 0;
function addMoreFields(srcHome, cloneHome) {
// Check if there isn't more than 3 fields
if(counter != 3) {
counter++;
// Create a child
var template = document.getElementById(srcHome).cloneNode(true);
// remove templet clone's id to avoid future confusion
template.id = "";
template.style.display = 'block';
/* Get the cloned templet's
* Children. Here we will make
* only the ones who have a name
* unique.
*/
var copy = template.childNodes;
for(var i = 0; i < copy.length; i++) {
var cloneName = copy[i].name;
if(cloneName)
copy[i].name = cloneName + counter;
}
// Locate clone's home
var endLocation = document.getElementById(copyHome);
// Place clone in home
endLocation.parentNode.insertBefore(Template,endLocation);
}
}
window.onload = function() {
addMreFields('SoupBox', 'SoupBowl');
}
html code
<td><div id="SnackBox" style="display:none">
<select id="dfood" name="dfood">
<option>--Select--</option>
<?php
$result = mysql_query("SELECT * FROM survival_mode.dryfood_t", $link);
while($row = mysql_fetch_array($result)) {
echo "\n\t\t\t\t\t\t<option value='{$row['dfood_ID']}'>{$row['dfood_name']}</option>";
}
echo "\n";
?>
</select>
<input name="df_qty" type="text" placeholder="qty" size="1" maxlength="1"/>
<?php
if($climate == "warm") {
echo "\n\t\t\t\t<input type='button' value='-' onclick='if(instance > 1){instance--; this.parentNode.parentNode.removeChild(this.parentNode);}' />";
echo "\n\t\t\t\t<input type='button' value='+' onclick='moreFields(\"SnackBox\", \"SnackPlate\");' />";
}
echo "\n";
?>
</div>
<span id="SnackPlate"></span>
</td>
<td><div id="SoupBox">
<select id="Soup" name="Soup">
<option>--Select--</option>
<?php
$result = mysql_query("SELECT * FROM survival_mode.soup_t", $link);
while($row = mysql_fetch_array($result)) {
echo "\n\t\t\t\t\t\t<option value='{$row['soup_ID']}'>{$row['soup_name']}</option>";
}
echo "\n";
?>
</select>
<input name="s_qty" type="text" placeholder="qty" size="1" maxlength="1" />
<?php
if($climate == "cold") {
echo "\n\t\t\t\t<input type='button' value='-' onclick='if(counter > 1){counter--; this.parentNode.parentNode.removeChild(this.parentNode);}' />";
echo "\n\t\t\t\t<input type='button' value='+' onclick='addMoreFields(\"SoupBox\", \"SoupBowl\");' />";
}
echo "\n";
?>
</div>
<span id="SoupBowl"></span>
</td>

jQuery Autocomplete with dynamic rows

I have the following jQuery code:
$(document).ready(function(){
var ac_config = {
source: "autocomplete-delta.php",
select: function(event, ui){
$("#del_item").val(ui.item.SKU);
if ((ui.item.CASE_PRICE) != "N/A"){
$("#del_price").val(ui.item.CASE_PRICE);
} else {
$("#del_price").val(ui.item.UNIT_PRICE);
}
},
minLength:1
};
$("#del_item").autocomplete(ac_config);
});
Which works fine for one line item, basically the line item takes an item name, which is the field you type in for autocomplete and then after selecting it fills the price field with either the unit price or case price from my DB. Now I want to have 18 of these rows which I set up through php to be del_item1, del_item2 etc. and when I tried the following code, the autocomplete works and it fills in the item fine, but the price field does not fill in, any ideas...?
$(document).ready(function(){
for (var i = 1; i < 19; i++) {
var ac_config = {
source: "autocomplete-delta.php",
select: function(event, ui){
$("#del_item" + i).val(ui.item.SKU);
if ((ui.item.CASE_PRICE) != "N/A"){
$("#del_price" + i).val(ui.item.CASE_PRICE);
} else {
$("#del_price" + i).val(ui.item.UNIT_PRICE);
}
},
minLength:1
};
$("#del_item" + i).autocomplete(ac_config);
});
Here is the php file that the JS references:
<?php
require_once "/home/default/support/default.php";
$dbh = showDB ();
$cities = array();
$sth = $dbh->prepare("SELECT * FROM purchase_items");
$sth->execute();
while($row = $sth->fetch(PDO::FETCH_ASSOC)) {
$cities[]=$row;
}
$term = trim(strip_tags($_GET['term']));
$matches = array();
foreach($cities as $city){
if((stripos($city['SKU'], $term) !== false) || (stripos($city['FAMILY'], $term) !== false) || (stripos($city['DESCRIPTION'], $term) !== false)){
// Add the necessary "value" and "label" fields and append to result set
$city['value1'] = $city['SKU'];
$city['value2'] = $city['FAMILY'];
$city['value3'] = $city['DESCRIPTION'];
$city['label'] = "{$city['FAMILY']} - {$city['DESCRIPTION']} ({$city['SKU']})";
$matches[] = $city;
}
}
$matches = array_slice($matches, 0, 100);
print json_encode($matches);
And here is the html side as requested above these are the 16 line items I'm working with, inside of a for loop the counter in the loop is $d:
if($d&1) { ?>
<div id="trow">
<? } else { ?>
<div id="trow" class="none">
<? } ?>
<div id="thirds" style="text-indent:5px;">
<input type="text" name="del_item<? echo("$d");?>" id="del_item<? echo("$d");?>" class="salesinput"
placeholder="Start typing item SKU, family, description..." style="text-align:left; width:95%;" />
</div>
<div id="dollar"><span class="tdblackbigger">$ </span></div>
<div id="lfamt" style="width:15%;"><input type="text" name="del_price<? echo("$d");?>" id="del_price<? echo("$d");?>" class="salesinput" style="text-align:right; padding-right:5px;" /></div>
<div id="lfsold" style="width:15%;"><input type="text" name="del_retail<? echo("$d");?>" id="del_retail<? echo("$d");?>" class="salesinput" /></div>
<div id="dollar"><span class="tdblackbigger">$ </span></div>
<div id="lfamt" style="width:15%;"><input type="text" name="del_line<? echo("$d");?>" id="del_line<? echo("$d");?>" class="salesinput" style="text-align:right; padding-right:5px;" /></div>
</div>

Insert values from multiple form (with multiple buttons) into the same textarea at cursor position

I want to insert values from another form field in one text area. There are multiple fields, each placed in different forms with different submit buttons. Whenever the button is clicked, the values in that form should be inserted into the text area.
The fields are generated in an array. I have assigned the same id name for every field. This is to make every field's values belong to that textarea. My problem is, only the first field insert its value into the textarea when I click its button.Other fields not working. How could I fix this?
Here is the code:
<script type="text/javascript">
window.onload = function() {
btn1 = document.getElementById("btnInsertText1");
myText1 = document.getElementById("myTextArea1");
text1 = document.getElementById("textToInsert1");
btn1.onclick = function(){
insertAtCursor(myText1, text1.value);
}
}
function insertAtCursor(myField, myValue) {
if (document.selection) {
myField.focus();
sel = document.selection.createRange();
sel.text = myValue;
}
else if (myField.selectionStart || myField.selectionStart == '0') {
var startPos = myField.selectionStart;
var endPos = myField.selectionEnd;
myField.value = myField.value.substring(0, startPos) + myValue + myField.value.substring(endPos, myField.value.length);
}
else {
myField.value += myValue;
}
}
</script>
<textarea id="myTextArea1" name="update" cols="85" rows="22">
Testing. Values from another field will be inserted here.
</textarea>
<?php
$ref = "
SELECT *
FROM reftext1_objective
WHERE projectid='$id'";
$refresult = mysql_query($ref);
while($row = mysql_fetch_array($refresult))
{?>
<form>
<input id="textToInsert1" type="text" value="<?php echo $row[$text];?>" readonly="true">
<input type="button" id="btnInsertText1" value="<<" />
</form><br><?php
}
As stated in my comment on the question, the problem is due to the duplicated element ids in the loop in your PHP code. To fix it, try this:
<script type="text/javascript">
$(function() {
var textarea = document.getElementById("myTextArea1");
$(".button").click(function() {
var $parentForm = $(this).closest("form");
var text = $(".insert-text", $parentForm).val();
insertAtCursor(textarea, text);
});
});
function insertAtCursor(myField, myValue) {
if (document.selection) {
myField.focus();
sel = document.selection.createRange();
sel.text = myValue;
}
else if (myField.selectionStart || myField.selectionStart == '0') {
var startPos = myField.selectionStart;
var endPos = myField.selectionEnd;
myField.value = myField.value.substring(0, startPos) + myValue + myField.value.substring(endPos, myField.value.length);
}
else {
myField.value += myValue;
}
}
</script>
<textarea id="myTextArea1" name="update" cols="85" rows="22">
Testing. Values from another field will be inserted here.
</textarea>
<?php
$ref = "SELECT * FROM reftext1_objective WHERE projectid = '$id'";
$refresult = mysql_query($ref);
while ($row = mysql_fetch_array($refresult))
{ ?>
<form>
<input class="insert-text" type="text" value="<?php echo $row[$text];?>" readonly="true">
<input type="button" class="button" value="<<" />
</form><br>
<?php }
?>
Example fiddle

Categories