I need to do comparing string because I need to have calculation. The string from select option in HTML and another will be the variable string.
This is my HTML Code:
<label>Freight Cost Mode</label>
<select class="form-control" id="freightcostmode_insert" name="freightCostMode_insert" onchange="val()">
<option>Percentage</option>
<option>Monetary</option>
</select>
<input class="form-control" id="freightcost_insert" type="text" placeholder="Freight Cost Mode" name="freightCost_insert" onkeyup="val()">
<input type="text" class="form-control" id="freight">
This is my javascript code:
<script>
function val() {
var input = document.getElementById("freightcostmode_insert").value;
var calculation = document.getElementById("freightCost_insert").value;
if(inputing == "Percentage"){
document.getElementById('freight').value = calculation*1.5;
}if else(inputing == 'Monetary'){
}
}
</script>
For first your inputing variable does not exist - maybe input.
For second parse the calculation value into a number.
Also you have some syntax errors in your code.
function val() {
var input = document.getElementById("freightcostmode_insert").value;
var calculation = document.getElementById("freightcost_insert").value;
if(input == "Percentage"){
document.getElementById('freight').value = parseInt(calculation) * 1.5;
} else if(input == 'Monetary'){
}
}
<label>Freight Cost Mode</label>
<select class="form-control" id="freightcostmode_insert" name="freightCostMode_insert" onchange="val()">
<option>Percentage</option>
<option>Monetary</option>
</select>
<input class="form-control" id="freightcost_insert" type="text" placeholder="Freight Cost Mode" name="freightCost_insert" onkeyup="val()">
<input type="text" class="form-control" id="freight">
Working Code
function val() {
var input = document.getElementById("freightcostmode_insert").value,
calculation = document.getElementById("freightcost_insert").value
document.getElementById('freight').value = input === "Percentage" ?
calculation * 1.5 : calculation * 2.5;
}
<label>Freight Cost Mode</label>
<select class="form-control" id="freightcostmode_insert" name="freightCostMode_insert" onchange="val()">
<option>Percentage</option>
<option>Monetary</option>
</select>
<input class="form-control" id="freightcost_insert" type="text" placeholder="Freight Cost Mode" name="freightCost_insert" onkeyup="val()">
<input type="text" class="form-control" id="freight">
Related
I have been browsing through similar questions but have found nothing that would fit the bill. I have three input / select fields and a working JS function to calculate the number. All I need now is to display it automatically upon the selection and number input.
function Calculate() {
var f1 = document.getElementById("item");
var field1 = parseInt(f1.options[f1.selectedIndex].value);
var f2 = document.getElementById("level");
var field2 = parseInt(f2.options[f2.selectedIndex].value);
var f3 = document.getElementById("number");
var field3 = parseInt(f3.value);
(field1 * field2 * field3) / 100;
}
<label for="item">Choose item:</label>
<select id="item" name="item" form="qForm" required>
<option value="empty"></option>
<option value="250">item1</option>
<option value="250">item2</option>
<option value="300">item3</option>
</select>
</br>
<label for="level">Choose level:</label>
<select id="level" name="level" form="qForm" required>
<option value="empty"></option>
<option value="100">lvl1</option>
<option value="120">lvl2</option>
<option value="140">lvl3</option>
</select>
</br>
<label for="number">Duration (hours):</label>
<input id="number" type="number" name="number" min="10" required>
</br>
<label for="price">Preliminary price (EUR):</label>
<input type="number" id="price" name="price" form="qForm" readonly value="Calculate()">
Can you help me, please, to find a way to display the JS function in the "number" input field automatically?
Thanks.
I tried the JS function with a button and alert() and it works just fine. However, I cannot make it appear in the input field as I hoped I would by assigning its value to the function.
You need to listen on change event on each of your 3 fields, and recalculate if something changed.
const f1 = document.getElementById("item");
const f2 = document.getElementById("level");
const f3 = document.getElementById("number");
const price = document.getElementById("price");
[f1,f2,f3].forEach(field=> field.addEventListener('change', Calculate));
function Calculate() {
try{
var field1 = parseInt(f1.options[f1.selectedIndex].value);
var field2 = parseInt(f2.options[f2.selectedIndex].value);
var field3 = parseInt(f3.value);
price.value = (field1 * field2 * field3) / 100;
}
catch(e){
console.log(e.message);
}
}
<label for="item">Choose item:</label>
<select id="item" name="item" form="qForm" required>
<option value="empty"></option>
<option value="250">item1</option>
<option value="250">item2</option>
<option value="300">item3</option>
</select>
</br>
<label for="level">Choose level:</label>
<select id="level" name="level" form="qForm" required>
<option value="empty"></option>
<option value="100">lvl1</option>
<option value="120">lvl2</option>
<option value="140">lvl3</option>
</select>
</br>
<label for="number">Duration (hours):</label>
<input id= "number" type="number" name="number" min="10" required>
</br>
<div>
<label for="price">Preliminary price (EUR):</label>
<input type="number" id="price" name="price" form="qForm" readonly value="Calculate()">
</div>
IMHO, I added a event listener "change" on each select input. When the 3 values are different than empty, I write the value :
let foo = document.getElementById("price");
let price = Calculate();
foo.value = price;
Of course, Calculate() will return the computed price.
I have a form which have two field "optin" and "Qty".The quantity field of the form accept the number.The minimum number which can be entered in this field(QTY) depends upon the the value of the Option field i.e. If the option fiels value is red then the minimum value propert of the Qty field should be 5 and if it is 'Red' then the minimum property of the Qty field should be 10. I am doing it by the given code but its not working.
<td><input type="text" name="option" onkeydown="random()" class="form-control" >
<script>
function random()
{
var a=document.getElementById('option').value;
if(a==="red")
{
var minimum = '5';
}
else if(a==="green")
{
var minimum= '10';
}
}
</script>
<input type="NUMBER" name="qty" class="form-control" min=<?php var minimum ?> ></td>
<!-- This is the code you provided -->
<td><input type="text" name="option" onkeydown="random()" class="form-control" >
<script>
function random()
{
var a=document.getElementById('option').value;
if(a==="red")
{
var minimum = '5';
}
else if(a==="green")
{
var minimum= '10';
}
}
</script>
<input type="NUMBER" name="qty" class="form-control" min=<?php var minimum ?> ></td>
Let's see...
First of all lets change your if else case with a switch:
switch(a){
case "red":
var minimum = 5;
break;
case "green":
var minimum = 10;
break;
}
Now I will remove the php tag and add a line to change the min value of the input.
<td><input type="text" id="option" onkeydown="random()" class="form-control" />
<script>
function random()
{
var a=document.getElementById('option').value;
switch(a){
case "red":
var minimum = 5;
break;
case "green":
var minimum = 10;
break;
}
document.getElementById("input").setAttribute("min", minimum)//this line adds an attribute or sets it to a given value
}
</script>
<input type="NUMBER" id="input" class="form-control" /></td>
Now let's see this code in action!
Run the following snippet.
<td><input type="text" id="option" onchange="random()" class="form-control" />
<script>
function random()
{
var a=document.getElementById('option').value;
switch(a){
case "red":
var minimum = 5;
break;
case "green":
var minimum = 10;
break;
}
document.getElementById("input").setAttribute("min", minimum)//this line adds an attribute or sets it to a given value
}
</script>
<input type="NUMBER" id="input" class="form-control" /></td>
And done! Also, I changed the onkeydown to onchange.
Added more rows in case there are many rows with the same fields.
Secondly, I have added an event listener instead of direct function
call but you can do either.
Extracting into calculatingMinimunQuantity for easier readibility
and calling setAttribute (min) there.
var options = document.querySelectorAll(".option");
options.forEach(function(option) {
option.addEventListener("change", function() {
calculatingMinimunQuantity(option);
});
});
function calculatingMinimunQuantity(option) {
var minimum = 0;
var value = option.value;
if (value === "red") {
minimum = "5";
} else if (value === "green") {
minimum = "10";
}
// getting the quantity input field
option.nextElementSibling.setAttribute("min", minimum);
}
<td>
<div>
<input type="text" class="option form-control" placeholder="option" name="option" />
<input type="NUMBER" class="form-control" name="qty" placeholder="quantity" />
</div>
</td>
<td>
<div>
<input type="text" class="option form-control" placeholder="option" name="option" />
<input type="NUMBER" class="form-control" name="qty" placeholder="quantity" />
</div>
</td>
I keep on getting this error Uncaught ReferenceError: calculatePrice is not defined at HTMLInputElement.onclick.
I have already seen the other answers on here regarding this error and none of them worked. I tried defining the script in body or head, didn't make a difference. I also think the function and button I connect it to are correct as I compared to a solution, so I really don't know why it is not working when I press it.
<html>
<head>
<link href="style/myStyles.css" type="text/css" rel="stylesheet">
<title> The Printing Company </title>
</head>
<body>
<script type="text/javascript"></script>
<script>
function calculatePrice() {
var quantity, type, price
quantity = document.getElementById("qty").value;
type = document.getElementById("cardstype").value;
if (type.includes("Basic"){
price = 10*(quantity/100);
} else if (type.includes("Medium"){
price = 15*(quantity/100);
} else if (type.includes("High"){
price = 20*(quantity/100);
}
alert("Your order will cost " + price + " GBP.");
}
</script>
<form action="form.php" method="post">
<label >Company Name</label><br>
<input name="name" type="text" required /><br>
<br>
<label>Contact email</label><br>
<input name="email" type="email" required /><br>
<br>
<label>Business Card type</label><br>
<select name="cardstype" id="cardstype">
<option value="" disabled selected>-Select Card Quality-</option>
<option value="Basic Quality">Basic Quality</option>
<option value="Medium Quality">Medium Quality</option>
<option value="High Quality">High Quality</option>
</select><br>
<br>
<label>Business Cards quantity</label><br>
<input name="qty" id ="qty" type="number" required Onchange = '
if( !( this.value >= 100 && this.value <= 1000 ) ) {
//alert the user that they have made a mistake
alert( this.value + " is not a valid quantity. Minimun quantity per order: 100 and maximum: 1000.");
this.value=""; //clears the text box
}'><br>
<br>
<input type="button" name="Price" value="Calculate Price" onclick="calculatePrice()"/>
<input type="submit" value="Submit Order"/>
</form>
</html>
Can anyone help?
I think You are missing the closing parentheses in your if statements:
if (type.includes("Basic") {
^^^ here
Working example:
function calculatePrice() {
var quantity, type, price;
quantity = document.getElementById("qty").value;
type = document.getElementById("cardstype").value;
if (type.includes("Basic")) {
price = 10*(quantity/100);
} else if (type.includes("Medium")) {
price = 15*(quantity/100);
} else if (type.includes("High")) {
price = 20*(quantity/100);
}
alert("Your order will cost " + price + " GBP.");
}
<form action="form.php" method="post">
<label >Company Name</label><br>
<input name="name" type="text" required /><br>
<br>
<label>Contact email</label><br>
<input name="email" type="email" required /><br>
<br>
<label>Business Card type</label><br>
<select name="cardstype" id="cardstype">
<option value="" disabled selected>-Select Card Quality-</option>
<option value="Basic Quality">Basic Quality</option>
<option value="Medium Quality">Medium Quality</option>
<option value="High Quality">High Quality</option>
</select><br>
<br>
<label>Business Cards quantity</label><br>
<input name="qty" id ="qty" type="number" required Onchange = '
if( !( this.value >= 100 && this.value <= 1000 ) ) {
//alert the user that they have made a mistake
alert( this.value + " is not a valid quantity. Minimun quantity per order: 100 and maximum: 1000.");
this.value=""; //clears the text box
}'><br>
<br>
<input type="button" name="Price" value="Calculate Price" onclick="calculatePrice(event)"/>
<input type="submit" value="Submit Order"/>
</form>
You have a few typos in your function:
Missing closing curly brace (looks fixed now)
Missing semicolon after variable definition: var quantity, type, price;
Mismatched parentheses in if/elseif conditions (3 times): if (type.includes("Basic")) {
The below code has these problems fixed:
<script>
function calculatePrice() {
var quantity, type, price;
quantity = document.getElementById("qty").value;
type = document.getElementById("cardstype").value;
if (type.includes("Basic")){
price = 10*(quantity/100);
} else if (type.includes("Medium")){
price = 15*(quantity/100);
} else if (type.includes("High")){
price = 20*(quantity/100);
}
alert("Your order will cost " + price + " GBP.");
}
</script>
Therefore, the function calculatePrice isn't defined and can't be called.
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.
Hi I'm new for programming and I'm facing one problem.
I have 3 input for values and 1 input for total. What I need is when I change the value in any input total should change automatically.
<input type="text" name="Amt" id="amount" class="form-control" />
<input type="text" name="Amt" id="amount" class="form-control" />
<input type="text" name="Amt" id="amount" class="form-control" />
And for total I have:
<input type="text" class="form-control" name="total" id="total" value="" />
And below is the script:
<script type="text/javascript">
$('#amount').change(function() {
$('#total').attr('value', function() {
var result = 0;
$('#amount').each(function() {
result += $(this).attr('value');
});
return result;
});
});
</script>
You have multiple ids for amount. These should be changed to classes. In addition, the value for each amount will be picked out by jQuery as a string, so that needs to be changed to an integer:
$('.amount').change(function () {
var result = 0;
$('.amount').each(function () {
result += +$(this).val();
});
$('#total').val(result);
});
Fiddle.