How to update each row of a dynamic PHP table - javascript

I am trying to change the quantity of each row based on the 'Amt' that is inputted in the last column of that row. It's a search table that's based off the Area #. Essentially I want the user to be able to input a location and move bulk items from the current area to the new area that was inputted. If the Amt would equal zero that row would be skipped and no update would take place. Otherwise it would create a new row in the database with the new data.
Link to screenshot
https://photos.google.com/photo/AF1QipP2HMqNFmv208VOOl2DvppPGiZkv7f_keD_f8tj
This is my php table code:
The values for country, region, location and placeid are stored in the dropdown.
<?php
if (isset($_GET['Placeid'])) {
$moveplace = $_GET['Placeid'];
$sql = "SELECT *
FROM Parts p, Locations l
WHERE Placeid = '$moveplace' and p.locationid = l.locationid";
$result = mysqli_query($conn, $sql);
$queryResult = mysqli_num_rows($result);
if ($queryResult > 0) {
$i = 1;
while ($row = mysqli_fetch_assoc($result)) {
if ($i % 2 == 0) {
$bgcolor = "rgba(199, 199, 199, 0.3)";
} else {
$bgcolor = "rgba(199, 199, 199, 0.8)";
}
echo "<div>
<input type='hidden' value='".$row['id']."' name='hiddensearchid'>
<input type='hidden' value='".$row['PartDescription']."' name='movedesc'>
<input type='hidden' value='".$row['BrandName']."' name='moveBN'>
<input type='hidden' value='".$row['CategoryName']."' name='moveCN'>
<input type='hidden' value='".$row['NSN_number']."' name='moveNSN'>
<input type='hidden' value='".$row['Image']."' name='moveimage'>
<table class=searcht style='background-color:$bgcolor'>
<tbody>
<tr>
<td value='".$row['PartNum']."' name='movepart'>".$row['PartNum']."</td>
<td value='".$row['ModelNum']."' name='movemodelnum'>".$row['ModelNum']."</td>
<td>".$row['Country']."</td>
<td>".$row['Region']."</td>
<td>".$row['Location']."</td>
<td>".$row['Placeid']."</td>
<td style='width:100px' value='".$row['UnitNum']."' name='moveunitnum'>".$row['UnitNum']."</td>
<td style='width:50px;' value='".$row['QTY']."' name='moveqty'>".$row['QTY']."</td>
<th style='width:50px; border-right:none;'><input style='width:20px; text-align:center;' value='0' type=text name='moveamt'></th>
</tr>
</tbody>
</table>
</div>";
$i++;
}
echo "<tr><td></td><td><input class='submit' type='submit' value='Confirm' name='submitPlacemove' onclick=\"return confirm ('Are you sure you want to submit?')\"></td></tr></form>";
}
}
I figure I need to use some sort of JavaScript but I'm new to it. Any help is appreciated.

I assume there is a Done button that the user will press when ready to scan the table for changes and update the database.
read and store the current values of the table (before any user changes)
When Done button clicked, scan table row-by-row and compare stored value with current value
When find a change, send the data over to a PHP file whose job is to update the back-end table with the new data (Note: you will need to send both the new data AND an item id, so it knows where to put the new data)
Here is a very rough, untested, simple example of what the code might look like:
var arr_old = [];
var arr_new = [];
$.each( $('table tr'), function(i, v){
if (i==0) return true; //ignore header row (return true === continue)
let currval = $(this).find('td:nth-child(3) index').val();
arr_old.push(currval);
});
$('#btnDone').click(function(){
$.each( $('table tr'), function(i, v){
if (i==0) return true; //ignore header row (return true === continue)
let row_id = $(this).find('td:nth-child(1)').text(); //1 or 2 or ...
let newval = $(this).find('td:nth-child(3) index').val();
if ( newval !== arr_old[i+1] ){
$.ajax({
type = 'post',
url = 'path/to/your/php_file.php',
data = 'item_id=' +row_id+ '&new_val=' +newval
}).done(function(recd){
console.log('Updated row ' + recd);
});
}
});
table{border-collapse:collapse;}
th,td{border:1px solid #ccc;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<table>
<tr><th>ID</th><th>Col 1</th><th>Edit Col</th></tr>
<tr><td>1</td><td>Summat</td><td><input class="bob" type="text" value="car" /></td></tr>
<tr><td>2</td><td>Other</td><td><input class="bob" type="text" value="bike" /></td></tr>
<tr><td>3</td><td>Summat</td><td><input class="bob" type="text" value="foot" /></td></tr>
</table>
<button id="btnDone">Done</button>
If you are new to javascript, I suggest using jQuery for these reasons
References:
update list with jquery & ajax
http://learn.jquery.com/about-jquery/how-jquery-works/
SLAKS jQuery Tutorial - Use right-arrow to display next bit of text

Related

How do you clear a specific JSON object in a JSON array within localStorage by a delete button?

I have a program that simply add's students to a table and stores that information into local-storage. I can add students and see the data stored into local-storage, but my big problem is figuring out how to remove a specific object within local storage upon button click after adding it (without clearing all of local storage).
Link for test: https://www.chriscaldwelldev.com/studentIA/student.html
Here is the table and inputs (HTML):
<body>
<div class="container">
<h1 class="title">Student Manager</h1>
<div class="controlCenter">
<table id="studentTable" class="table">
<thead>
<tr>
<th>Student Number:</th>
<th>Name:</th>
<th>Address:</th>
<th>Phone Number:</th>
<th>GPA:</th>
<th>Academic Plan:</th>
<th>Level:</th>
<th>Status:</th>
</tr>
</thead>
<tbody id="students"></tbody>
<tbody>
<tr>
<td><input type="text" id="studentN"></td>
<td><input type="text" id="name"></td>
<td><input type="text" id="address"></td>
<td><input type="text" id="phoneN"></td>
<td><input type="text" id="gpa"></td>
<td><input type="text" id="ap"></td>
<td><select id="selectL" name="SelectL">
<option value="" disabled selected>Select...</option>
<option value="freshman">Freshman</option>
<option value="sophomore">Sophomore</option>
<option value="junior">Junior</option>
<option value="senior">Senior</option>
<option value="graduate">Graduate</option>
</select></td>
<td><select id="selectS" name="SelectS">
<option value="" disabled selected>Select...</option>
<option value="active">Active</option>
<option value="inactive">Inactive</option>
</select></td>
</tr>
</tbody>
</table>
<input id="add" class="addButton" value="ADD">
</div>
</div>
</body>
Here is the JS:
// when the document loads
$(function(){
// add an onclick function to the id=add button
$("#add").click(function(){
var studentN = $("#studentN").val();
var name = $("#name").val();
var address = $("#address").val();
var phoneN = $("#phoneN").val();
var gpa = $("#gpa").val();
var ap = $("#ap").val();
var selectL = $("#selectL").val();
var selectS = $("#selectS").val();
if(studentN==null || name==null || address==null || phoneN==null ||
gpa==null || ap==null || selectL==null || selectS==null){
alert("All Fields Are Required to Add a Student");
return;
}
//create JSON object with text inputs with key:value pairs
var student = {
studentN: studentN,
name: name,
address: address,
phoneN: phoneN,
gpa: gpa,
ap: ap,
selectL: selectL,
selectS: selectS
}
//load local storage
var students = JSON.parse(localStorage.getItem("students"));
//if empty
if(!students){
students = [];
}
students.push(student);
localStorage.setItem("students", JSON.stringify(students));
// store a copy of the row in the body
var row = $("<tr>");
// store a copy of the current state in the <td> tag
var studentNData = $("<td>");
// now change the innerHTML for that <td>
studentNData.html(studentN);
// append the new value to our row
row.append(studentNData);
(...)
// store a copy of the current state for the next <td> tag
var selectSData = $("<td>");
// change the inner html of the <td>
selectSData.html(selectS);
// append the new value to our row
row.append(selectSData);
var deleteButton = $("<td>" + "<input type=\"button\" class=\"deleteButton\" value=\"X\">");
row.append(deleteButton);
// on the DOM, put the new row on the top of the list
$("#students").prepend(row);
// reset the values of the text inputs to empty strings
$("#studentN").val("");
$("#name").val("");
$("#address").val("");
$("#phoneN").val("");
$("#gpa").val("");
$("#ap").val("");
$("#selectL").val("");
$("#selectS").val("");
});
var students = JSON.parse(localStorage.getItem("students"));
$("#studentTable").on('click', '.deleteButton', function () {
$(this).closest('tr').remove();
//I can't think of what to do here...
});
if (students) {
// loop through the entire JSON array stored in local storage
for (i in students) {
// get a current copy of the content in the row
var row = $("<tr>");
// store a copy of the current state in the <td> tag, update the innerHTML, then append it to the DOM at the end of the row
var studentNData = $("<td>");
studentNData.html(students[i].studentN);
row.append(studentNData);
(...)
var selectSData = $("<td>");
selectSData.html(students[i].selectS);
row.append(selectSData);
var deleteButton = $("<td>" + "<input type=\"button\" class=\"deleteButton\" value=\"X\">");
row.append(deleteButton);
// now add the row to the DOM at the beginning of the list
$("#students").prepend(row);
}
}
});
I assume that whatever I need to do primarily needs to be done in the deleteButton onclick. I've thought some ideas through but they seem super wrong. I appreciate any help if you can.
One solution you could use is adding a data-studentn attribute to your delete buttons. Then, when the delete button is clicked, you can load the students array from localStorage, remove the student with that studentn, and save the new students array.
Change
"<input type=\"button\" class=\"deleteButton\" value=\"X\">"
to
"<input type=\"button\" class=\"deleteButton\" value=\"X\" data-studentn=\"" + students[i].studentN + "\" >"
Note: Remember to do something similar in the other place where you create a delete button.
Under //I can't think of what to do here... you can do the following:
var deletedStudentN = $(this).attr('data-studentn');
var students = JSON.parse(localStorage.getItem("students"));
students = students.filter(function(student) {
return student.studentN != deletedStudentN;
});
localStorage.setItem("students", JSON.stringify(students));

Extract multiple values from a MySQL table into HTML

I want to get three values from a MYSQL table, and display them in a text area. I can get only one value. If it possible, I want to save this selector, because it is critical to my program.
JavaScript:
function getsteel() {
var material = document.getElementsByName("option");
if (material[3].checked == true) {
var g = document.getElementById("selector1");
var str = g.options[g.selectedIndex].value;
document.getElementById('kr').value = str;
}
}
HTML:
<td>k<sub>r</td></sub>
<td>
<input type="text" id="kr" disabled style="width:50px;">
</td>
<td>[MPa]</td>
PHP:
<?php
mysql_connect("localhost","root","");
mysql_select_db("db-user22777");
//query
$sql=mysql_query("SELECT * FROM steels ORDER BY id ASC");
if(mysql_num_rows($sql)){
$select= '<select id="selector1" disabled size="12">';
while($r=mysql_fetch_array($sql)){
$select.='<option value="'.$r['kr'].'">'.$r['Steelname'].' | '.$r['kr'].' [MPa]</option>';
}
}
$select.='</select>';
echo $select;
?>
Thanks for any help provided!

HTML / JQuery: Email an Entire Div/Table

I want to be able to email content such as a div that is in my webpage using the php mail function and possible putting it on the so called "Thank Your, Your Email Sent" page. However, I'm running into some issues. I am following this Email Div Content, Email div text content using PHP mail function, and GET entire div with its elements and send it with php mail function questions that has already been posted as a guide but it doesn't seem to be working for me. I want to send via email and show up on the "Thank Your, Your Email Sent" page within the message. Anything I'm doing wrong?
HTML Table that I want to send over is:
<div id="add_items_content" style="width:100%;">
<center>
<table id="add_item_here" style="width:98%;">
<tbody>
<tr><td>Item</td><td>Years</td><td>Quantity</td><td>Training Hours</td><td>Total Item Cost</td></tr>
</tbody>
</table>
</center>
<center>
<table id="add_totals_here" style="width:98%;">
<tbody>
<tr><td cospan="3"> </td><td> </td><td> </td></tr>
</tbody>
</table>
</center>
</div>
<script>
$(document).ready(function(){
$('table[id^=add_item_here]').hide();
$('table[id^=add_totals_here]').hide();
$('div[id^=office_submit]').hide();
$('div[id^=show_form]').hide();
//First obtaining indexes for each checkbox that is checked
$('input[name=item_chk]').change(function(){
var index = this.id.replace('item_chk','');
if($(this).is(':checked')){
AddNewItem(index);
}else{
RemoveItem(index);
}
CalculateTotals();
});
function AddNewItem(index){
// Get hidden variables to use for calculation and tables.
var item = $('#item_chk'+index).parent().text().trim();
var itemdescr = $('#itemdescr'+index).val();
var traininghrs = parseInt($('#traininghrs'+index).val());
var qty = parseInt($('#qty'+index).val());
var yrs = parseInt($('#yrs'+index).val());
var item_cost = 0;
// Calculating item cost for just that one checkbox
item_cost+=parseInt($('#servicefee'+index).val());
item_cost*=parseInt($('#yrs'+index).val());
item_cost+=parseInt($('#licensefee'+index).val());
item_cost*=parseInt($('#qty'+index).val());
var traininghrs = parseInt($('#traininghrs'+index).val());
//Display each item that is checked into a table
$('#add_item_here tr:last').after('<tr id="row_id'+index + '"><td style=\"width:35%;\">' + itemdescr +'</td><td style=\"width:15%;\" >' + yrs +'</td><td style=\"width:16%;\">' + qty +'</td><td style=\"width:18%;\">' + traininghrs + '</td><td style=\"width:16%;\">$'+ item_cost + '</td></tr>');
}
function RemoveItem(index){
$('table#add_item_here tr#row_id'+index).remove();
}
function CalculateTotals(){
var total_cost = 0;
var total_training = 0;
$('input:checkbox:checked').each(function(){
var index = this.id.replace('item_chk','');
var item_cost = 0;
// Calculating item cost for just that one checkbox
item_cost+=parseInt($('#servicefee'+index).val());
item_cost*=parseInt($('#yrs'+index).val());
item_cost+=parseInt($('#licensefee'+index).val());
item_cost*=parseInt($('#qty'+index).val());
var traininghrs = parseInt($('#traininghrs'+index).val());
total_cost +=item_cost;
total_training +=traininghrs;
});
if(total_cost > 0 || total_training > 0) {
$('#add_totals_here tr:last').children().remove();
$('#add_totals_here tr:last').after('<tr ><td colspan="3" style=\"width:66%;\">TOTALS:</td><td style=\"width:18%;\">' + total_training + '</td><td style=\"width:16%;\">$'+ total_cost + '</td></tr>');
$('#add_item_here').show();
$('#add_totals_here').show();
$('#office_submit').show();
}else{
$('table[id^=add_item_here]').hide();
$('table[id^=add_totals_here]').hide();
$('div[id^=office_submit]').hide();
}
}
$("input[name='office_submit']").click(function () {
$('#show_form').css('display', ($(this).val() === 'Yes') ? 'block':'none');
});
// Quantity change, if someone changes the quantity
$('select[name=qty]').change(function(){
var index = this.id.replace('qty','');
if($("#item_chk"+index).is(':checked')){
RemoveItem(index);
AddNewItem(index);
CalculateTotals();
}
});
// Years change, if someone changes the years
$('select[name=yrs]').change(function(){
var index = this.id.replace('yrs','');
if($("#item_chk"+index).is(':checked')){
RemoveItem(index);
AddNewItem(index);
CalculateTotals();
}
});
})
</script>
Trial Number 1; So far I have tried:
<script>
function mail_content() {
var tablesContent = document.getElementById("add_items_content").innerHTML;
$.post('send_form.email.php',{content:tablecontent},function(data) {
});
}
</script>
Using script I have added to the send_form_email.php:
<?php
$txt = $_POST['content'];
mail($to,$subject,$message,$txt,$headers);
mail($from,$subject2,$message2,$txt,$headers2);
?>
Trial Number 2: I even tried storing it into a hidden field:
<input name="data" id="data" type="hidden" value=""></input>
<script type="text/javascript">
$(document).ready(function(){
$("#price_quote").submit(function() { //notice submit event
$("#my_hidden_field").val($("#add_items_content").html()); //notice html function instead of text();
});
});
</script>
And then the send_form_email.php I put it in that message see if it even shows up.
$txt = $_POST['data'];
$message = "Content: ".$txt."\n";
mail($to,$subject,$message,$txt,$headers);
mail($from,$subject2,$message2,$txt,$headers2);
Trial Number 3: Even tried Ajax
<script>
function mail_content(){
var html = $('#add_items_content').html();
$.ajax(function{
type="POST",
url:"send_form_email.php",
data:"data="+html,
success:function(response){
$('#add_items_content').show().html("email sent");
}
});
}
</script>
What am I missing or doing wrong? Why doesn't the div / tables show up or display?
You really should check your JS console for errors:
var tablesContent = document.getElementById("add_items_content").innerHTML;
^---note the "sC"
$.post('send_form.email.php',{content:tablecontent},function(data) {
^--note the c
JS vars are case sensitive, and will NOT magically correct typos for you.
And then there's this:
<input name="data" id="data" type="hidden" value=""></input>
^---id 'data'
$("#my_hidden_field").val($("#add_items_content").html());
^--- completely DIFFERENT ID

Delete table rows should not allow to delete last row

I have a table and I am deleting the table rows using the following script:
$("#ordertable tr input:checked").parents('tr').remove();
Then I am updating the table ids as follows:
function updateRowCount(){
var table = document.getElementById("ordertable");
var rowcountAfterDelete = document.getElementById("ordertable").rows.length;
for(var i=1;i<rowcountAfterDelete;i++) {
table.rows[i].id="row_"+i;
table.rows[i].cells[0].innerHTML=i+"<input type='checkbox' id='chk_" + i + "'>";
var j = i+1;
$("#ordertable tr:nth-child("+j+")").find("td").eq(1).find("select").attr("id","pn_"+i);
$("#ordertable tr:nth-child("+j+")").find("td").eq(2).find("input").attr("id","notes_"+i);
$("#ordertable tr:nth-child("+j+")").find("td").eq(3).find("input").attr("id","qty_"+i);
table.rows[i].cells[4].id = "pdctid_"+i;
}
}
I need a condition in such a way that user can not allow to delete last row.
I mean in deletion If user marked last row checkbox then I should get an alert.
It seems you want to not delete the last row with a checked checkbox. So you'd get the row to be deleted, then get the row with the last checked checkbox. If they're the same row, don't delete. Otherwise, delete.
The following is just an example of putting the above algorithm to the test. Of course there is much to improve to suit your circumstance.
E.g.
function deleteRow(el) {
// Get the row candidate for deletion
var row = el.parentNode.parentNode;
// Get last checked checkbox row, if there is one
var table = row.parentNode.parentNode;
var cbs = table.querySelectorAll('input:checked');
var cbRow = cbs.length? cbs[cbs.length - 1].parentNode.parentNode : null;
// If the row to be deleted is the same as the last checked checkbox row
// don't delete it
if (row === cbRow) {
alert("Can't touch this...");
// Otherwise, delete it
} else {
row.parentNode.removeChild(row);
}
}
<table>
<tr>
<td>0 <input type="checkbox">
<td><button onclick="deleteRow(this)">Delete row</button>
<tr>
<td>1 <input type="checkbox">
<td><button onclick="deleteRow(this)">Delete row</button>
<tr>
<td>2 <input type="checkbox">
<td><button onclick="deleteRow(this)">Delete row</button>
</table>

Display array of products one by one by brand

I have a code in which i want to display product list from array.
I am getting around 1000 products from an array of n number of brands.n can be 1,2,3..etc.
I want to display 2 products of one brand then 2 products from second brand and then 2 from next brand and so on it should be repeated while displaying..
Homepage.php
<html>
<head>
<title>Insert title here</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<style type="text/css">
#image{
width:250px;
height:250px;
border:1px solid black;
}
</style>
</head>
<body>
<script type="text/javascript">
function get_check_value() {
var c_value = [];
$('input[name="brand"]:checked').each(function () {
c_value.push(this.value);
});
return c_value.join(',');
}
function get_disc_value(){
var d_value=[];
$('input[name="discount"]:checked').each(function () {
d_value.push(this.value);
});
return d_value.join(',');
}
$(document).ready(function(){
checkboxValidate = function (e) {
if(e)e.preventDefault();
//alert("hi");
//var os = $('#originState').val();
//var c = $('#commodity').val();
//var ds = $('#destState').val();
var ser = get_check_value();
var disc=get_disc_value();
//var queryString = "os=" + os;
var data = "?ser=" + ser;
var queryString = "&ser=" + ser;
// alert(ser);
$.ajax({
//alert("ajax");
type: "POST",
url: "sortingajax.php",
data: {ser:ser,disc:disc},
dataType : 'html',
success: function (b) {
// alert(a+' ok. '+b)
$('#results').html(b);
console.log(b);
}
});
}
$( "[type=checkbox]" ).change(checkboxValidate);
checkboxValidate();
});
</script>
brand
<input type="checkbox" name="brand" value="Sunbaby" id="check" />Sunbaby
<br/>
<input type="checkbox" name="brand" value="Advance Baby" id="check"/>Advance Baby
<br/>
store
<br/>
<input type="checkbox" name="discount" value="10" />10
<br/>
<input type="checkbox" name="discount" value="20" />20
<br/>
<input type="checkbox" name="discount" value="30" />30
<br/>
<button id="btnSubmit">sort</button>
<div id="image">
<img src="http://img5a.flixcart.com/image/sunglass/4/u/y/mb-d4-09b-miami-blues-free-size-275x275-imadzkhuchryqjgp.jpeg" width="250px" height="250px"/>
</div>
<div id="results">
sdfsdfsdfsdfdsfgsdgsbsfgvf
</div>
</body>
</html>
sortingajax.php
<?php
include('connection.php');
$query=$_POST['ser'];
$query2=$_POST['disc'];
$query=explode(",",$query);
$query = array_filter($query);
$query2=explode(",",$query2);
$query2 = array_filter($query2);
$result=count($query);
$result1=count($query1);
//echo $result;
echo $query;
echo $query1;
echo $result1;
$parts = array();
$brandarray=array();
$discarray=array();
$limit = 10;
$offset = 0;
foreach( $query as $queryword ){
$brandarray[] = '`BRAND` LIKE "%'.$queryword.'%"';
}
foreach( $query2 as $discword ){
$discarray[] = '`DPERCENT` < "'.$discword.'"';
}
"/>
I want to display 2 products of one brand first and then 2 from second one and then from next brands.But according to above code it displays all products from one brand and then from next brand....Please guide me on how to change above code product list brand by brand..
based on a quick overview of your code, you seem to be adding the first element from each product to the array and then the second and then the third etc.. until you reach the highest count.
try instead, first limiting the max to only 2 instead of the max (so in this case, $highest_number should =2)
and second, add 1 brand, then the next then the next, instead of all at once, as unless you are handling it some other way would interlace each of the brands. I dont know if thats what you want?
does this help?
I've spent a little time looking at your code and am not entirely sure how it works. It seems like there's got to be an easier way to do this. Can you start a counter and cut off your loops once it hits the counter?
$i = 0;
$all_products = array();
while($row = mysql_fetch_array($firstsql3)) {
if (++$i <= 2) {
// DO YOUR STUFF HERE
$product_name = $row['product_name']; // GET THE PRODUCT NAME FROM THE DB
$product_color = $row['product_color'];
$product_size = $row['product_size'];
$individual_product_array = array(); // CREATE A NEW ARRAY FOR THIS PRODUCT
$individual_product_array['color'] = $product_color;
$individual_product_array['size'] = $product_size;
$all_products[$product_name][] = $individual_product_array;
}
}
If you insert _POST vars in mysql queries like this you will be hacked immediately see :
'`BRAND` LIKE "%'.$queryword.'%"';

Categories

Resources