Update an input field when another input field is updated - javascript

I can't get this to work.
I got two forms, "mult" and "mult2" with a script making some simple calculations running through both. Both fields are dependent on data in another form called "recipe".
The thing is, i can actually get one of the forms to work doing it like i have done (see all my code under here) - the weird thing is that it's only mult2 that works and does all the calculations. Mult1 is not doing anything. The fields that needs to be updated in the end is "gravity" and "gravity2" - and only "gravity2" gets updated with the result of the calculation.
I know it's some long code bits here, but hope you can help me..
Here is the "recipe" form:
<form name="recipe">
<input type="text" size="1" maxlength="3" name="batchVal" value="30" onChange="calculate(malt1); calculate(malt2)"></td>
<input type="text" size="1" maxlength="3" name="efficiencyVal" value="75" onChange="calculate(malt1); calculate(malt2)"></td>
</form>
Here is the two forms, "mult" and "mult2" that both need the same datainputs from "recipe" form:
<form name="mult">
<select id="malt" name="malt" onChange="UpdateNextField(this,'ppg')">
<option>Choose fermentable..</option>
<?php
$query = $mysqli->prepare("SELECT id,maltname,maltebc,maltppg FROM malt WHERE mainid = ?");
$mainidcolumn = "1";
/* bind parameters */
$query->bind_param("i", $mainidcolumn);
$query->execute();
$menu_result = $query->get_result();
/* now you can fetch the results into an array */
while ($menu = $menu_result->fetch_assoc()) {
echo '<option value="'.$menu['maltppg'].'">' . $menu['maltname'] . ' ' . $menu['maltebc'] . ' EBC</option>';
}
echo '</select>';
?>
<input type="text" id="ebcfield" size="1" maxlength="3">
<input type="text" name="weightVal" size="1" maxlength="5" value="0" onChange="calculate(malt1)">
<input name="grainpercent" type="text" id="grainpercent" size="1" maxlength="2">
<input type="text" id="gravity" size="1" value="0" maxlength="4">
<input name="graincolor" type="text" id="graincolor" size="1" maxlength="3">
<input type="text" name="ppgVal" id="ppg" onMouseMove="calculate(malt1)">
</form>
<form name="mult2">
<select id="malt" name="malt" onChange="UpdateNextField(this,'ppg2')">
<option>Choose fermentable..</option>
<?php
$query = $mysqli->prepare("SELECT id,maltname,maltebc,maltppg FROM malt WHERE mainid = ?");
$mainidcolumn = "1";
/* bind parameters */
$query->bind_param("i", $mainidcolumn);
$query->execute();
$menu_result = $query->get_result();
/* now you can fetch the results into an array */
while ($menu = $menu_result->fetch_assoc()) {
echo '<option value="'.$menu['maltppg'].'">' . $menu['maltname'] . ' ' . $menu['maltebc'] . ' EBC</option>';
}
echo '</select>';
?>
<input type="text" id="ebcfield" size="1" maxlength="3">
<input type="text" name="weightVal2" size="1" maxlength="5" value="0" onChange="calculate(malt2)">
<input name="grainpercent" type="text" id="grainpercent" size="1" maxlength="2">
<input type="text" id="gravity2" size="1" value="0" maxlength="4">
<input name="graincolor" type="text" id="graincolor" size="1" maxlength="3">
<input type="text" name="ppgVal2" id="ppg2" onMouseMove="calculate(malt2)">
</form>
And finally the javascript that does the calculations based on data in the input fields. Calculate(malt1) and Calculate(malt2) does the same thing, it's just two instances of the same calculation.
<script type = "text/javascript">
function UpdateNextField(which,ppg) {
document.getElementById(ppg).value = which.value;
}
function UpdateNextField(which,ppg2) {
document.getElementById(ppg2).value = which.value;
}
</script>
<!-- calculations for malt 1-5 -->
<!-- form 1 - fermentable 1 -->
<script type="text/javascript">
function calculate(malt1){
var weightVal = document.mult.weightVal.value;
var ppgVal = document.mult.ppgVal.value;
var batchVal = document.recipe.batchVal.value;
var efficiencyVal = document.recipe.efficiencyVal.value;
var showValue = 0;
var showValue = ((weightVal * ppgVal * 0.000008345) * (efficiencyVal) * 10) / batchVal + (1000);
showValue = Math.round(showValue * 1) / 1;
if (!isNaN(showValue)) {
document.getElementById('gravity').value = showValue;
}
}
function calculate(malt2){
var weightVal2 = document.mult2.weightVal2.value;
var ppgVal2 = document.mult2.ppgVal2.value;
var batchVal = document.recipe.batchVal.value;
var efficiencyVal = document.recipe.efficiencyVal.value;
var showValue2 = 0;
var showValue2 = ((weightVal2 * ppgVal2 * 0.000008345) * (efficiencyVal) * 10) / batchVal + (1000);
showValue2 = Math.round(showValue2 * 1) / 1;
if (!isNaN(showValue2)) {
document.getElementById('gravity2').value = showValue2;
}
}
</script>

You have a few problems with your function names and duplicate IDs, as noted by Jay and LcLk. But, assuming you fix these, you can save a lot of time and grief by using jQuery. For example:
HTML
<input type="text" id="first" />
<input type="text" id="second" />
Javascript
$("#first").keypress(function(){
/* your custom code goes here */
console.log("A key was pressed.");
});
What this says is that anytime a key is pressed while the first input is selected, it will print out A key was pressed in the console. You can then either directly call your calculation functions from within that anonymous inner function, or pass them directly into keypress();.

Related

How to pass 2 variables from select element embedded into php to javascript function?

I have an associative array $row[Description, Name, ID_Item]. When a user select "Name" by event onchange into function I want to pass 2 variables $row[Description] and $row[ID_Item].
So, I guess it should be something like:
<form action="/delete.php" method="post">
<select name="NameSelect" id="ID_Select" onchange = "ShowItemInfo('.$row['ID_Item'].', '.$row['Description'].' ,)">
<?php
while ($row = $res->fetch_assoc())
{
echo '<option value = " '.$row['Description'].''.'¶'.''.$row['ID_Item'].' " > '.$row['Name'].' </option>';
}
mysqli_free_result($res);
mysqli_close($conn);
?>
</select>
It doesn't work, so can anybody help? Because due to inability to pass these variables I have to pass them via DOM with separator "¶" but it is obviously a crutch:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Delete your records</title>
</head>
<body>
<h2>
<?php
$conn = mysqli_connect("www.mywebsite.com", "username", "password", "Goods")
or die ('Cannot connect to db');
$query = "select ID_Item, Name,Description from Item";
$res = mysqli_query($conn, $query);
?>
<form action="/delete.php" method="post">
<select name="NameSelect" id="ID_Select" onchange = "ShowItemInfo()">
<?php
while ($row = $res->fetch_assoc())
{
echo '<option value = " '.$row['Description'].''.'¶'.''.$row['ID_Item'].' " > '.$row['Name'].' </option>';
}
mysqli_free_result($res);
mysqli_close($conn);
?>
</select>
<button type="submit"> Delete! </button>
<br> <br> <br> <br>
<textarea id="Desc" name="Desc" rows="4" cols="50" readonly>
Please, choose an item!
</textarea>
<br><br><br><br>
<label for="ID_Item">Identificator of an item:</label>
<input type="number" id="ID_Item" name="ID_Item" value="42" readonly >
</form>
</h2>
<script>
function ShowItemInfo() {
var str = document.getElementById("ID_Select").value;
var res = str.split("");
var Id = 0;
var Description = "";
var i = 1;
while (res[i] != "¶") {
Description = Description.concat(res[i]);
i++;
}
for (var j = i+1; j < res.length - 1; j++) {
Id = 10 * Id + parseInt(res[j],10);
}
document.getElementById("Desc").value = Description;
document.getElementById("ID_Item").value = Id;
}
</script>
</body>
</html>
Instead of adding values using separator you can use custom html attributes and set one value inside these attributes . So , your php code for options will look like below :
echo '<option desc=".$row['Description']." value = ".$row['ID_Item']." > '.$row['Name'].' </option>';
Demo Code :
function ShowItemInfo() {
//get selector
var selector = document.getElementById("ID_Select")
var Id = selector.value; //value
var Description = selector.options[selector.selectedIndex].getAttribute("desc"); //custom attribute desc
//set them
document.getElementById("Desc").value = Description;
document.getElementById("ID_Item").value = Id;
}
<select name="NameSelect" id="ID_Select" onchange="ShowItemInfo()">
<option desc="soemthing1" value="1"> sss</option>
<option desc="soemthing2" value="2"> sss2</option>
<option desc="soemthing3" value="3"> sss3</option>
</select>
<button type="submit"> Delete! </button>
<br> <br> <br> <br>
<textarea id="Desc" name="Desc" rows="4" cols="50" readonly>
Please, choose an item!
</textarea>
<br><br><br><br>
<label for="ID_Item">Identificator of an item:</label>
<input type="number" id="ID_Item" name="ID_Item" value="42" readonly>
Update 1 :
You can achieve same by passing value whenever onchange event is called .
Demo Code :
function ShowItemInfo(Id, Description) {
//set them
document.getElementById("Desc").value = Description;
document.getElementById("ID_Item").value = Id;
}
<!--pass values as parameter using `this`-->
<select name="NameSelect" id="ID_Select" onchange="ShowItemInfo(this.value,this.options[this.selectedIndex].getAttribute('desc'))">
<option desc="soemthing1" value="1"> sss</option>
<option desc="soemthing2" value="2"> sss2</option>
<option desc="soemthing3" value="3"> sss3</option>
</select>
<button type="submit"> Delete! </button>
<br> <br> <br> <br>
<textarea id="Desc" name="Desc" rows="4" cols="50" readonly>
Please, choose an item!
</textarea>
<br><br><br><br>
<label for="ID_Item">Identificator of an item:</label>
<input type="number" id="ID_Item" name="ID_Item" value="42" readonly>

Auto Update Amount (USD) using onchange with javascript

I need help with this code. I have looked at tons of related questions but none has helped so far. Please help. These are exactly what I need:
To auto-update "Amount(USD)" once the value of "Amount(NGN)" is changed. Preferably with Vanilla Js.
I would also like to pick the final value of "Amount(USD)" and store in a PHP session to use in other pages.
See my code below:
<?php $grandTotal=10; ?>
<script type="text/javascript">
function calculateTotal() {
var nairaRate = document.pricecalculator.nairaRateToday.value; //get NGN rate today from admin and assign to nairaRate
dollarValue = eval(document.pricecalculator.nairaInput.value * nairaRate); //multiply nairaInput by nairaRate to get dollarValue
document.getElementById('dollar').innerHTML = dollarValue; //pass dollarValue to dollar to show auto-calculation onscreen
}
</script>
<form name="pricecalculator" action="">
<legend>Price Calculator (Buy BTC)</legend>
<label>Amount (NGN)</label><input type="number" name="nairaInput" onchange="calculateTotal()" value="1" /> <br />
<label>Amount (USD):</label><span id="dollar">1</span> <br />
<input type="hidden" name="nairaRateToday" value="<?= $grandTotal ?>">
</form>
I was able to solve the problem like this:
<?php $grandTotal=10; ?> // set PHP variable
<form name="pricecalculator" action="">
<legend>Price Calculator (Buy BTC)</legend>
<label>Amount (NGN)</label><input type="number" id="naira-input" name="naira-input" onchange="calculateTotl()" value="1"/> <br />
<label>Amount (USD):</label><span id="dollar">1</span> <br />
</form>
<script type="text/javascript">
function calculateTotl() {
var nairaRate = document.getElementById("naira-input").value;
// Select your current input
let phpval = "<?= $grandTotal ?>"; // grab php value
var dollarResult = document.querySelector('#dollar');
var total = Number(nairaRate) * Number(phpval); evaluate current input * php value
return dollarResult.innerHTML = total; // write result to #dollar
}
</script>
Try this (worked for me):
var ngn = document.getElementById('ngn');
var dollar = document.getElementById('dollar');
ngn.onchange = ()=>{dollar.innerText=ngn.value*0.0026}
Check the following code. I have used a hardcoded value, that is 7 as nairaRate
let nairaInput = document.querySelector("input[name='NairaValue']")
nairaInput.addEventListener('change', (e) => calculateTotal(e.target.value, 7))
function calculateTotal(input, nairaRate) {
var resultInDollar = document.querySelector('#dollar');
var total = Number(input) / Number(nairaRate);
return resultInDollar.innerHTML = total
}
<form name="pricecalculator" action="">
<legend>Price Calculator (Buy BTC) Naira At 7</legend>
<label>Amount (NGN)</label><input type="number" name="NairaValue" onchange="calculateTotal()" value="0" /> <br />
<label>Amount (USD):</label><span id="dollar">0</span> <br />
<input type="hidden" name="nairaRateToday" value="<?= $grandTotal ?>">
</form>
Good Luck!

Saving form data into dynamic form when hitting back or refreshing page

Right now I have code to dynamically add input fields to my form. I want to be able to submit the data and go to the next page but if someone decides to go back, the newly made input fields would still be there with the data. The way I have it set up now is to echo onto the input fields which works with the first two but not the third.
When I hit back, I get this:
Here is my code:
<h2>Enter Beneficiaries for Tangible Personal Property:</h2>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<div class="input_fields_container">
<tr>
<td>Name:<input type="text" name="ben[]" value="<?php echo $_SESSION['ben']['0'];?>" class="form-control name_list" /></td>
<td>Percentage of tangible personal property:<input type="number" min="0" max="100" value="<?php echo $_SESSION['percent']['0'];?>" style="width: 40px" name="percent[]" class="form-control name_list" /></td>
<td><input type="button" name="add" id="add" class="add_more_button" value= "Add Another" ></input></td>
</tr>
</table>
</div>
<p style="color:red;"></p>
<h3>Enter Contingent Beneficiary: </h3>
Name:<input type="text" name="conben" value="<?php echo $_SESSION['conben'];?>" >
<br><br>
<button type="button" name="back" value="back" onclick="location.href='county.php'">Back</button>
<input type="submit" name="submitform" value="Next"></input>
<button type="button" name="download" onclick="location.href='downloadAdd.php'">Download will</button>
</form>
<script>
//script to add/remove fields
$(document).ready(function () {
var getControl=getCookie("countControls1");
var max_fields_limit = 2; // Set limit for maximum input fields
var x = 0; // Initialize counter for text box
for(var i=1; i<=getControl; i++) {
console.log(i);
addControls();
}
$('.add_more_button').click(function (e) { // Click event to add more fields
addControls();
});
function addControls()
{
console.log(x);
if (x < max_fields_limit ) {
x++; // Increment counter
setCookie("countControls1",x,100);
$('.input_fields_container').append('<div><tr id="row'+x+'"><td> Name:<input type="text" name="ben[]" value="<?php echo $_SESSION['ben']['1'];?>" class="form-control name_list" /></td><td>&nbspPercentage of tangible personal property:<input type="number" min="0" max="100" style="width: 40px" name="percent[]" value="<?php echo $_SESSION['percent']['1'];?>" class="form-control name_list" /></td><td>Remove</td></tr>');; // Add input field
}
else if (x==2){
$("p").text("*Only 3 tangible beneficiaries are allowed.");
}
}
$('.input_fields_container').on("click", ".remove_field", function (e) { // User click on remove text links
$(this).parent('div').remove();
x--;
$("p").text("");
setCookie("countControls1",x,100);
});
function setCookie(cname,cvalue,exdays)
{
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires=" + d.toGMTString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
$("#div1").html("Add cookie = ",getCookie(cname));
}
function getCookie(cname)
{
console.clear();
var name = cname + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.split(';');
//console.log(cname);
//console.log(decodedCookie);
console.log(ca);
for(var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
console.log(c.substring(name.length, c.length));
return (c.substring(name.length, c.length));
}
}
return "";
}
});
</script>
Is there anyway to achieve this in this way or do I need to implement something else?
You can just write the fields back using a loop because presumably you have the two arrays in your session. You should also use empty() or isset() to check if the session arrays exist first otherwise you will end up with warnings about undefined keys and such:
<tr>
<td>Name:<input type="text" name="ben[]" value="<?php echo $_SESSION['ben']['0'];?>" class="form-control name_list" /></td>
<td>Percentage of tangible personal property:<input type="number" min="0" max="100" value="<?php echo $_SESSION['percent']['0'];?>" style="width: 40px" name="percent[]" class="form-control name_list" /></td>
<td><input type="button" name="add" id="add" class="add_more_button" value= "Add Another" /></td>
</tr>
<?php
# Remove the first keys since you already used them above
unset($_SESSION['percent'][0],$_SESSION['ben'][0]);
# Just do a normal loop to create any remaining values
foreach($_SESSION['percent'] as $key => $value): ?>
<tr>
<td>Name:<input type="text" name="ben[]" value="<?php echo $_SESSION['ben'][$key];?>" class="form-control name_list" /></td>
<td>Percentage of tangible personal property:<input type="number" min="0" max="100" value="<?php echo $value; ?>" style="width: 40px" name="percent[]" class="form-control name_list" /></td>
</tr>
<?php endforeach ?>

How to multiple (a*b) two input text value and show it Dynamicly with text change in javascript?

i want to show the money that customer must pay and my inputs are like this :
<input type="text" class="form-control" placeholder="cost " id="txt" name="credit">
<input type="text" class="form-control" placeholder="quantity" id="txt" name="limit">
when the input text is changing i want to show the total cost (quantity*cost) in a <p> tag Dynamicly how can it be with javascript?
You can try this:
<input type="text" class="form-control" placeholder="cost " id="credit" name="credit" onchange="calculate()">
<input type="text" class="form-control" placeholder="quantity" id="limit" name="limit" onchange="calculate()">
<p id="result"></p>
And javascript part:
function calculate() {
var cost = Number(document.getElementById("credit"));
var limit = Number(document.getElementById("limit"));
document.getElementById("result").innerHTML= cost*limit;
}
You must ensure you entered numbers in inputs.
All of the above will generate errors if both the boxes are blank . Try this code , its tested and running .
<script>
function calc()
{
var credit = document.getElementById("credit").value;
var limit = document.getElementById("limit").value;
if(credit == '' && limit != '')
{
document.getElementById("cost").innerHTML = parseInt(limit);
}
else if(limit == '' && credit != '')
{
document.getElementById("cost").innerHTML = parseInt(credit);
}
else if(limit!= '' && credit!= '')
{
document.getElementById("cost").innerHTML = parseInt(limit) * parseInt(credit);
}
else
{
document.getElementById("cost").innerHTML = '';
}
}
</script>
</head>
<input type="number" value="0" min="0" class="form-control" placeholder="cost" id="credit" name="credit" onkeyup="calc();">
<input type="number" value="0" min="0" class="form-control" placeholder="quantity" id="limit" name="limit" onkeyup="calc();">
<p id="cost"></p>
Hope this will be useful
// get cost field
var _cost = document.getElementById("cost");
_cost.addEventListener('keyup',function(event){
updateCost()
})
// get quantity field
var _quantity = document.getElementById("quantity");
_quantity.addEventListener('keyup',function(event){
updateCost()
})
function updateCost(){
var _getCost = document.getElementById("cost").value;
var _getQuantity = document.getElementById("quantity").value;
var _total = _getCost*_getQuantity;
console.log(_total);
document.getElementById("updateValue").textContent = ""; // Erase previous value
document.getElementById("updateValue").textContent = _total // update with new value
}
jsfiddle
In case you consider using JQuery I've made this fiddle.
See if it works for you.
https://fiddle.jshell.net/9cpbdegt/
$(document).ready(function() {
$('#credit').keyup(function() {
recalc();
});
$('#limit').keyup(function() {
recalc();
});
function recalc() {
var credit = $("#credit").val();
var limit = $("#limit").val();
var result = credit * limit;
$("#result").text(result);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="form-control" placeholder="cost " id="credit" name="credit" value="0">x
<input type="text" class="form-control" placeholder="quantity" id="limit" name="limit" value="0">
<p id="result">0</p>
Try this:
<script >
function myFunction() {
document.getElementById('totalcost').innerHTML = document.getElementById('txt').value * document.getElementById('txt2').value;}
</script>
Also, change your HTML to this:
<input type="text" onkeypress="myFunction()" onkeyup="myFunction()" onclick="myFunction()" onmousemove="myFunction()" class="form-control" placeholder="cost " id="txt" name="credit">
<input type="text" onkeypress="myFunction()" onkeyup="myFunction()" onclick="myFunction()" onmousemove="myFunction()" class="form-control" placeholder="quantity" id="txt2" name="limit">
Enter cost and quantity.
Note the change with the second input: id='txt' was changed to id='txt2'. This is because no 2 elements can have the same id.
Note: Untested.

2 name attributes for a field in a form

I have a script that calculates the values in each and shows the calulated values. At the end it also calculates the already calculated values from all div's
Here is the html code:
<td>
<div>
<input name="r" class="rate" type="text" maxlength="255" size="5" value />
<input name="p" class="pack" type="text" maxlength="255" size="5" value />
<span class="amount"></span>
</div>
</td>
<td>
<div>
<input name="r" class="rate" type="text" maxlength="255" size="5" value />
<input name="p" class="pack" type="text" maxlength="255" size="5" value />
<span class="amount"></span>
</div>
</td>
The problem is that I want to put all fields in a form and then submit them to a database.
However, all divs contain two input fields with name "r" and "p".
So, I am kind of stuck here because I cannot figure out how to make the names unique or how to have them passed to the DB using POST.
This is what the calculating script looks like:
<script type="text/javascript">//<![CDATA[
//any time the amount changes
$(document).ready(function() {
$('input[name=r],input[name=p]').change(function(e) {
var total = 0;
var $row = $(this).parent();
var rate = $row.find('input[name=r]').val();
var pack = $row.find('input[name=p]').val();
total = parseFloat(rate * pack);
//update the row total
$row.find('.amount').text(total);
var total_amount = 0;
$('.amount').each(function() {
//Get the value
var am= $(this).text();
console.log(am);
//if it's a number add it to the total
if (IsNumeric(am)) {
total_amount += parseFloat(am, 10);
}
});
$('.total_amount').text(total_amount);
});
});
//isNumeric function Stolen from:
//http://stackoverflow.com/questions/18082/validate-numbers-in-javascript-isnumeric
function IsNumeric(input) {
return (input - 0) == input && input.length > 0;
}
//]]>
</script>
HTML:
<input type="text" name="r[]">
<input type="text" name="p[]">
<hr>
<input type="text" name="r[]">
<input type="text" name="p[]">
<hr>
<input type="text" name="r[]">
<input type="text" name="p[]">
PHP:
for ($i = 0; $i < count($_POST['p']); $i++) {
$rate = $_POST['r'][$i];
$pack = $_POST['p'][$i];
// do something with $rate and $pack
}
Since the browser submits all inputs (even if no value has been entered) and by specification it submits them in the order they are defined in the HTML code, you can rely that the elements in the two $_POST arrays will line up and the corresponding rate and pack will be received at the same index in the respective array.

Categories

Resources