I am creating a quote/order page that includes different types of options for the order all of which are calculated differently. I have a javascript function that will take the values inputed into the text boxes onchange and add a total at the bottom of a page. The issue I'm running into is the base product can be multiple lengths and many option prices are calculated by the foot. So what I have done is made a hidden field that stores the length of the base product and drop down menus to select the option. I have another javascript function that multiplies these two values and puts the total in one of the text boxes that should be auto summed with the first function. Both work perfectly independent of each other, however the issue I have is that the "on change command for the sum function isn't being recognized when the multiplication function auto updates the text box...
Any Help is very greatly appreciated.
Code...
<script type="text/javascript">
function multiplyLengthWalls(){
var length = parseInt(document.getElementById('length').value, 10);
var walls = parseInt(document.getElementById('walls').value, 10);
var total = length*walls;
document.getElementById('wallstotal').value = total;
}
</script>
<script type="text/javascript">
function sumCost() {
var arr = document.getElementsByName('featuretotal');
var tot = 0;
for(var i=0; i<arr.length;i++){
if(parseInt(arr[i].value))
tot += parseInt(arr[i].value);
}
document.getElementById('totalcost').value = tot;
}
</script>
HTML....
<td><select name="walls" id="walls" onchange="multiplyLengthWalls()">
<?php
do {
?>
<option value="<?php echo $row_walls['dcost']?>"><?php echo $row_walls['name']?></option>
<?php
} while ($row_walls = mysql_fetch_assoc($walls));
$rows = mysql_num_rows($walls);
if($rows > 0) {
mysql_data_seek($walls, 0);
$row_walls = mysql_fetch_assoc($walls);
}
?>
</select></td>
<td><label for="wallstotal"></label>
<input type="text" name="featuretotal" id="wallstotal" class="test" onchange="sumCost()"/></td>
</tr>
<tr>
<td>Ceiling:</td>
<td><label for="ceiling"></label>
<select name="ceiling" id="ceiling">
<?php
do {
?>
<option value="<?php echo $row_ceiling['dcost']?>"><?php echo $row_ceiling['name']?></option>
<?php
} while ($row_ceiling = mysql_fetch_assoc($ceiling));
$rows = mysql_num_rows($ceiling);
if($rows > 0) {
mysql_data_seek($ceiling, 0);
$row_ceiling = mysql_fetch_assoc($ceiling);
}
?>
</select></td>
<td><label for="ceilingtotal"></label>
<input type="text" name="featuretotal" id="ceilingtotal" class="test" onchange="sumCost()"/></td>
</tr>
<tr>
<td>Floor:</td>
<td><label for="floor"></label>
<select name="floor" id="floor">
<?php
do {
?>
<option value="<?php echo $row_floor['dcost']?>"><?php echo $row_floor['name']?></option>
<?php
} while ($row_floor = mysql_fetch_assoc($floor));
$rows = mysql_num_rows($floor);
if($rows > 0) {
mysql_data_seek($floor, 0);
$row_floor = mysql_fetch_assoc($floor);
}
?>
</select></td>
<td><label for="floortotal"></label>
<input type="text" name="featuretotal" id="floortotal" class="test" onchange="sumCost()"/></td>
</tr>
</table>
<p> </p>
</div>
<div id="structural">structural</div>
<div id="hidden">hidden --
<input name="length" type="hidden" id="length" value="<?php echo $row_models['length']; ?>" />
</div>
</div>
<div id="footer">
<div id="total">total:<input name="totalcost" type="text" id="totalcost" readonly="readonly" /></div>
Related
I have rewritten my question to better elaborate as to what I am trying to accomplish and what I have tried thus far.
I have a table on my website which dynamically loads the table rows from a database. I have successfully integrated the jQuery UI "Sortable" and "Draggable" functionality to this page. the outcome is the numeric value changes as you are dragging the rows above or below their neighboring rows and as a result always update the first column of numbers within the table.
Here is the table
<form action="" method="post" id="sort_picks">
<div class="sort-picks-container">
<table class="table-preference-order" id="sortable">
<tbody class="ui-sortable">
<?php
$counter = 1;
foreach ( $result as $query ){
$pickcheck = "SELECT * FROM picks";
$pickcutoffcheck = $wpdb->get_results( $wpdb->prepare ($pickcheck, OBJECT_K ));
foreach ($pickcutoffcheck as $pickcutoffresult) { ?>
<div style="display:none;"><?php echo $pickcutoffresult->pickCutoff; ?></div>
<?php } ?>
<?php $maxlimit = $wpdb->get_row("SELECT count(*) as CNT1 FROM picks where User='$userid'" ); ?>
<tr class="ui-state-default preference-row">
<td class="index preference-pick-order">
<input type="text" class="pick-order" id="sort" name="sort[]" pattern="[1-<?php echo $maxlimit->CNT1; ?>]{1,2}" value="<?php echo $counter; ?>" style="border:0px;max-width:60px;font-size:20px;" readonly>
</td>
<td class="preference-pick-order">
<input type="text" name="rem[]" class="borderless" style="text-align:left;width:25px;display:none;" value="<?php echo $query->REM; ?>" readonly><?php echo $query->REM; ?>
</td>
<td class="preference-emp-info">
<input type="text" name="empname[]" class="borderless" style="display:none;" value="<?php echo $query->EmpName; ?>" readonly><b><?php echo $query->EmpName; ?></b>
</td>
<td class="preference-start-class">
<input type="text" name="starttime[]" class="borderless" style="text-align:left;max-width:75px;display:none;" value="<?php echo $query->StartTime; ?>" readonly><?php echo $query->StartTime; ?>
</td>
<td class="preference-details">
<input type="text" name="job_details[]" class="borderless" value="<?php echo $query->Job_Details; ?>" readonly style="display:none;"><?php echo $query->Job_Details; ?>
<br>
<input type="text" name="startdate[]" class="borderless" style="font-weight:bold;width:100%;text-align:left;display:none;" value="<?php if($query->StartDate!=""){echo date('l\, F jS Y', strtotime($query->StartDate)); }?>" readonly><?php if($query->StartDate!=""){echo date('l\, F jS Y', strtotime($query->StartDate)); }?>
</td>
</tr>
<?php $counter++; ?>
<?php }?>
</tbody>
</table>
</div>
<br>
<div class="sorters-holder">
<button onclick="upNdown('up');return false;" class="sorters">∧ </button><br>
<button onclick="upNdown('down');return false;" class="sorters">∨</button>
</div>
<div style="display:block;margin:auto;text-align:center;">
<input type="submit" name="submit[]" value="Next" class="job-select-submit" id="validate"> <input type="button" onclick="window.history.go(-1); return false;" value="Back" class="job-select-submit">
</div>
</form>
This is the working jQuery script
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.js"></script>
<script src="../wp-content/themes/Excellence_At_Work/jquery.ui.touch-punch.min.js"></script>
<script>
var $j = jQuery.noConflict();
var sort;
$j(function() {
$j("#sortable tbody").sortable({
change: function(event, ui) {
sort = 0;
$j('#sortable tr.ui-state-default:not(".ui-sortable-helper")').each(function() {
sort++;
if ($j(this).hasClass('ui-sortable-placeholder'))
ui.helper.find('td input[name^=sort]').attr('name', 'sort[]').attr('value', sort).val(sort);
else
$j(this).find('td input[name^=sort]').attr('name', 'sort[]').attr('value', sort).val(sort);
});
}
});
$j("#sortable tbody").disableSelection();
});
</script>
<script>jQuery('#sortable').draggable();</script>
As you can see in the html code, I have successfully integrated the buttons that I need to relocate the rows however when doing so I need the value of the first td to also update accordingly as does the drab and drop method. What would I add to the below javascript to get the value of the input with the name sort[] to change to its corresponding numeric place within the table rows newly changed order onclick?
<script>
var order; // variable to set the selected row index
function getSelectedRow()
{
var table = document.getElementById("sortable");
for(var i = 0; i < table.rows.length; i++)
{
table.rows[i].onclick = function()
{
if(typeof order !== "undefined"){
table.rows[order].classList.toggle("selected");
}
order = this.rowIndex;
this.classList.toggle("selected");
};
}
}
getSelectedRow();
function upNdown(direction)
{
var rows = document.getElementById("sortable").rows,
parent = rows[order].parentNode;
if(direction === "up")
{
if(order > 0){
parent.insertBefore(rows[order],rows[order - 1]);
// when the row go up the index will be equal to index - 1
order--;
}
}
if(direction === "down")
{
if(order < rows.length){
parent.insertBefore(rows[order + 1],rows[order]);
// when the row go down the index will be equal to index + 1
order++;
}
}
}
</script>
I hope this better explains whatt I am trying to accomplish. I have hit a road block and could really use some insight, thanks in advance for all those who can provide insight.
UPDATE
I have been able to successfully update the rows first td values onclick by adding the following script after order-- and order++ however this solution is causing the input fields to drop out of the td. Any insight on how to modify this script to include the input field?
Array.prototype.forEach.call(document.querySelectorAll('td:first-child'), function (elem, idx) {
elem.innerHTML = idx + 1;
FINAL UPDATE
I have succeeded in my mission and with a minor adjustment to the snippet from the last update I was able to get the form above working as noted.
Array.prototype.forEach.call(document.querySelectorAll('td:first-child input[name^=sort]'), function (elem, idx) {
elem.value = idx + 1;
By changing
'td:first-child'
to
'td:first-child input[name^=sort]'
I was able to reference the specific input field as opposed to all input fields in the first td column and no longer am replacing the input fields with plain text.
FINAL UPDATE
I have succeeded in my mission and with a minor adjustment to the snippet from the last update I was able to get the form above working as noted.
Array.prototype.forEach.call(document.querySelectorAll('td:first-child input[name^=sort]'), function (elem, idx) {
elem.value = idx + 1;
By changing
'td:first-child'
to
'td:first-child input[name^=sort]'
I was able to reference the specific input field as opposed to all input fields in the first td column and no longer am replacing the input fields with plain text.
I am working on a very simple php page. The user picks how many numbers they would like to be added up, then enters the numbers on the new page, clicks a button, and then the sum is displayed.
I cannot figure out how to add up the numbers though since I can't just assign variables to each number because of the loop. I've tried this not using loops, assigning variables to each one, and simply making the button add those variables, but that required making the code for the inputs many many times, and I want this to work with a loop in case I wanted to integrate the choice to pick hundreds of numbers or something. If php isn't the best thing for this, please let me know what would be better, but anyways... how do I add up the numbers that the user inputs?
Index page:
<p>How many number would you like to add?</p>
2<br>
3<br>
4<br>
5<br>
Calculator page:
<?php
$inputs = $_GET['inputs'];
?>
<div>Enter the numbers<br>
<?php
for ($x=0; $x < $inputs; $x++) {
echo '<input type="number"><br>';
}
?>
</div>
<form action='' method='post'><input type='submit' value='Find value' name='findvalue'></form>
<?php
if (isset($_POST['findvalue'])) {
}
?>
for ($x=0; $x < $inputs; $x++) {
echo '<input type="number"><br>';
}
You cant use input without any name. You can use dynamic name, for example:
for ($x=0; $x < $inputs; $x++) {
echo '<input type="number" name="number_'.$x.'"><br>';
}
Or better way to use array names:
for ($x=0; $x < $inputs; $x++) {
echo '<input type="number" name="number[]"><br>';
}
After that, var_dump your $_POST variable.
But, best way to create dynamic fields is creating one and clone it with javascript, when user want to add next value. Example with jQuery:
<div class="myInputs"><input type="number" name="numbers[]"></div>
Add input
<script>
$('#Add').click(function(){
$('.myInputs input:first').clone().appendTo(".myInputs");
return false;
});
Try this:
<?php
$inputs = $_GET['inputs'];
?>
<form action='' method='post'>
<div>Enter the numbers<br>
<?php
for ($x=0; $x < $inputs; $x++) {
echo '<input name="numbers[]" type="number"><br>';
}
?>
</div>
<input type='submit' value='Find value' name='findvalue'>
</form>
<?php
if (isset($_POST['findvalue'])) {
print_r($_POST["numbers"]);
}
?>
There is currently no JavaScript on your page. To interact with the client, JavaScript would be the best choice since there is no need to go to the backend to create input fields unless you need to save the number before interacting with the user
window.onload = function() {
document.getElementById("nums").onchange = function() {
var fields = document.getElementById("fields"),
numberOfField = parseInt(this.value, 10),
inputs = [];
for (var i = 0; i < numberOfField; i++) {
inputs.push('<input type="text" class="calcField" name="number' + i + '" />');
}
fields.innerHTML = inputs.length > 0 ? inputs.join("<br/>") : "";
}
document.getElementById("calc").onsubmit = function() {
var total = 0,
fields = document.querySelectorAll(".calcField");
for (var i = 0; i < fields.length; i++) {
var val = parseInt(fields[i].value, 10);
total += isNaN(val) ? 0 : val;
}
document.getElementById("total").value=total;
return false; // stop submission - remove to submit the form
}
}
<p>How many numbers would you like to add?</p>
<form id="calc">
<select id="nums">
<option value="0">Please select</option>
<option value="2">Two numbers</option>
<option value="3">Three numbers</option>
<option value="4">Four numbers</option>
</select>
<div id="fields"></div><hr/>
<input type="submit" value="Find value" /> <input type="text" id="total" />
</form>
try adding a hidden field for the number of inputs then use it to loop
<?php
$inputs = $_GET['inputs'];
?>
<form action='' method='post'><input type='submit' value='Find value' name='findvalue'>
<div>Enter the numbers<br>
<input type="hidden" name="numberofinputs" value="<?php echo $inputs;?>"/>
<?php
for ($x=0; $x < $inputs; $x++) {
//Please note the $x
echo '<input type="number'.$x.'"><br>';
}
?>
</div>
</form>
<?php
if (isset($_POST['findvalue'])) {
$numberOfinputs = $_POST['numberofinputs'];
for($i=0; $i<numberOfinputs; $i++){
//You can access it here
echo $_POST['number'.$i];
}
}
?>
Referring to this post. Add form fields dynamically populated dropdown list with php I have used his code but will modify it to fit my needs since I pretty much nothing about javascript. I have everything working except when you press the + button it never creates more input boxes. Any help would be great.
This my php file
<?php
session_start();
require_once("dbconfig.php");
?>
<html>
<head>
<script type="text/javascript" src="addfish.js"></script>
</head>
<form id="form1" name="form1" method="post" action="results.php">
<div id="itemRows">
<select name="species">
<option value="">Select Species</option>';
<?php $stmt = $dbc->prepare("SELECT species FROM fish");
$stmt->execute();
while($speciesq = $stmt->fetch(PDO::FETCH_ASSOC))
{
echo "<option value=\"" . $speciesq['species'] ."\">" . $speciesq['species'] ."</option>";
}
?>
</select>
Number: <input type="text" name="speciesnumber1" size="7" /> Weight: <input type="text" name="speciesweight1" /> <input onClick="addRow(this.form);" type="button" value="+" />
</div></form>
</html>
My addfish.js file
var rowNum = 0;
var ddsel = '<select name="species'+rowNum+'>';
var ddopt = '<option value="">Select Species</option>';
var ddselc= '</select>';
;
function addRow(frm) {
rowNum ++;
$.post("getlist.php", function(data) {
var frm = document.getElementById('form1')
for (var i=0; i<data.length; i++) {
ddopt += '<option value="'+data[i].value+'">'+data[i].value+'</option>';
}
var row = '<p id="rowNum'+rowNum+'">'+ddsel+ddopt+ddselc+'Number: <input type="text" name="speciesnumber'+rowNum+'" size="7" value="'+frm.speciesnumber1.value+'"> Weight: <input type="text" name="speciesweight'+rowNum+'" value="'+frm.speciesweight.value+'"> <input type="button" value="-" onclick="removeRow('+rowNum+');"></p>';
jQuery('#itemRows').append(row);
frm.add_qty.value = '';
frm.add_name.value = '';
}, "json");
}
function removeRow(rnum) {
jQuery('#rowNum'+rnum).remove();
}
This is my getlist.php
<?php
session_start();
include("dbconfig.php");
$stmt = $dbc->prepare("SELECT species FROM fish");
$stmt->execute();
$result = array();
while ($rows = $stmt->fetch(PDO::FETCH_ASSOC)){
$result[] = array(
'value' => $rows['species'],
);
}
echo json_encode($result);
?>
Your code is using jQuery, but I don't see where you include this library. Try to put this code before include addfish.js in header :
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
If you need to add rows with this fields dynamically I suggest you make a row which is the original row:
<div class="rows" data-rows="1">
<div class="row row-first">
<select name="row[0][select_name]">
<option value="1">Some value</option>
</select>
<input type="text" name="row[0][text_name]" />
</div>
</div>
and the javascript
<script type="text/javascript">
$('#add_row').on('click', function(){
var row = $('.row-first').clone(); // Clone the first row
var rows = parseInt($('.rows').attr('data-rows'));
rows++;
$('.rows').attr('data-rows', rows);
row.removeClass('row-first'); // Prevent multiple rows cloning
$(row).find('[name]').each(function(){
var name = $(this).attr('name');
name = name.replace(/\[[0-9+]\]/, '[' + rows + ']');
$(this).attr('name', name);
$(this).val("").change(); // Null the select
});
$('.rows').append(row);
});
</script>
So what you do is clone the first row and remove the class, which you search. Increment the rows count and replace all names in you row with the new row number e.g. row[0][name] becomes row[1][name], and append the row.
Also when you edit the rows you MUST put set the data-rows to the exact number. You can do it like count($myRows). And when you write the remove row function DO NOT REMOVE the first row.
Hope it hepls.
// You can use this
var row = '<p id="rowNum'+rowNum+'">'+ddsel+ddopt+ddselc+'Number: <input type="text" name="speciesnumber'+rowNum+'" size="7" value="'+$($(frm).find('input[name="speciesnumber1"]')[0]).val()+'"> Weight: <input type="text" name="speciesweight'+rowNum+'" value="'+$($(frm).find('input[name="speciesnumber1"]')[0]).val()+'"> <input type="button" value="-" onclick="removeRow('+rowNum+');"></p>';
jQuery('#itemRows').append(row);
I'm using a text box as a "quantity" field that updates a < p > with the subtotal of the item. I have this working great for the first item in my while loop (php). Each consecutive item does not adjust the span however.
My PHP:
<?php $furniture = mysql_query("SELECT * FROM tbl_furniture WHERE furniture_active = '1'");
while($row = mysql_fetch_array($furniture))
{
?>
<div class="one-third column">
<h3><img src="images/<?php echo $row['furniture_image1'];?>" width="300" height="300"></h3>
<?php $furniture_price = $row['furniture_price'];
$furniture_id = $row['furniture_id'];?>
<div id="content">
<table width="100%" border="0">
<tr>
<td class="price">
<p class="furn_itemprice" id="price">£<?php echo $furniture_price;?></p><input name="price[]" type="hidden" value="<?php echo $furniture_price;?>"><input name="furniture_id[]" type="hidden" value="<?php echo $furniture_id;?>">
</td>
<td class="quantity">
<input name="qty[]" type="text" id="quantity" value="" class="calc"/><br />
</td>
</tr>
</table>
<br />
<p class="totals" id="subtotal">Sub-total:</p>
</div>
</p>
<?php } ?>
With the javascript function looking like this:
var stock = {}
window.onload=function() {
var inputs = document.getElementsByTagName('input');
for (var i=0;i<inputs.length;i++) {
if (inputs[i].type=="text" && inputs[i].id.indexOf('quantity')!=-1) {
var name = inputs[i].id.replace('quantity','');
stock[name] = parseFloat(document.getElementById('price').innerHTML.replace('£',''))
inputs[i].onchange=function() {
var total = 0;
for (var furn_item in stock) {
var q = document.getElementById("quantity").value;
total += (isNaN(q) || q=="")?0:parseInt(q)*stock[furn_item]
}
document.getElementById('subtotal').innerHTML="Sub-total: £"+total.toFixed(2);
}
}
}
}
I'm not sure what I need to do, but I presume somehow the problem lies with the Sub-total: not having a unique id/name??
you could give each element a unique id like:
<?php $furniture = mysql_query("SELECT * FROM tbl_furniture WHERE furniture_active = '1'");
$i=0 // init counter
while($row = mysql_fetch_array($furniture))
{...
...
<p class="furn_itemprice" id="price<?php echo $i++;?>">£<?php ec... // append counter to element id
...
and
var q = document.getElementById("quantity"+i).value;
Also you should not use mysql* for new code, it's been superceeded by mysqli*
personally I prefer PDO for php database connections
As said in the comment, your code generates multiple HTML elements with the same id. An id must be unique on the entire page. That's why your code doesn't work.
What you want to achieve is to give different ids for every row / piece of furniture and bind the JavaScript handlers accordingly. It's easier with jQuery. You could create quantity fields that have an attribute that contains the price:
<input name="qty[]" type="text" data-price="<?php echo $furniture_price;?>" value="" class="quantity"/>
Then, in jQuery, you could get all elements with the class quantity:
var sum = 0;
$(".quantity").each(function() {
sum += $(this).val() * $(this).attr('data-price');
});
$("#subtotal").text(sum);
So, you can achieve something similar without jQuery, for sure. I hope this gives you an idea how to solve your problem.
my html code
<?php
while($results = $user_class->fetch_array($sql)){
?>
<input type="text" name="price[]" class="price" id="price"
size="5px" readonly value="<?php echo $results['price_v'] ?>">
<select onChange="update(); return false;" name="qty[]" class="quant">
<option value="0"></option>
<?php
$limit = $results['limiter'];
for($i=1;$i <= $limit;$i++ ){
?>
<option value="<?php echo $i?>"><?php echo $i?></option>
<?php } ?>
</select>
this is my jquery code
$("#example_form tr.raww").each(function(i,o){
if($(o).find(".quant").val()>0) {
total += $(o).find(".quant").val() * $(o).find(".price").val();
}
});
if i attach
<script type="text/javascript" src="http://code.jquery.com/mobile/1.4.0/jquery.mobile-1.4.0.min.js"></script>
My jQuery can't read the value from the field.
And if i remove that jquery mobile can read value from field.
http://jsfiddle.net/QJxYv/3/
Is there anything wrong with my jQuery code?
Your code will work as long as there is only one element with class quant and one element with class price in each row of class raww.
Try the following:
if ($(this).find("select.quant").val() > 0) {
and
sub_total += $(this).find("select.quant").val() * $(this).find(".price").val();
Updated fiddle:
http://jsfiddle.net/QJxYv/4/