I got a problem, I have two text fields, both have a value by default when open the page or reaload, values the I get from MySQL and PHP, like this:
<input type="text" id="field1" value="<?php echo $first_value; ?>" />
<input type="text" id="utility" value="<?php echo $second_value; ?>" />
And with javascript I would like to do that when I change the value of #field1 do a subtraction and show the result into #utility.
The problem is that the result of the operation isn't correct, for example:
if #field1 has 500 the first time and #utility 1041.00 and now if I change the value of #field1 with 1000 the new value for #utility is -69.06, I guess it is doing the operation everytime that I delete or add a new number but I have no idea how to fix this, this is my javascript (jquery) code:
$('#field1').on('input', function() {
var difference = parseFloat($(this).val());
var utility = $('#utility').val().replace(/,/g, '');
var total = utility - difference;
if (!total) { total = 0; }
$('#utility').val(parseFloat(Math.round(total * 100) / 100).toFixed(2));
});
Your other option without adding extra fields would be to use .on('blur',function(){} ) or simply .blur(function(){})
This would cause the action to take place when input left the field forcing the refresh.
I solved my problem by creating a new input field type hidden with the same value of #utility and I named it as #new_utilty
$('#field1').on('input', function() {
var difference = parseFloat($(this).val());
var utility = $('#new_utility').val().replace(/,/g, '');
var total = utility - difference;
if (!total) {
total = 0;
$('#utility').val(parseFloat(Math.round(utility * 100) / 100).toFixed(2));
} else {
$('#utility').val(parseFloat(Math.round(total * 100) / 100).toFixed(2));
}
});
And this was my solution without Ajax Call
Related
I constructed a calculation form out of different modules and got it to work except for 1 element.
The overall calculation is build up as (value + value = total), and the values are all regular numbers.
However, the last bit I added is a 'percentage'-value which is 10% of the first value in the form. So as an example:
Value 1 = 50,
Percent value 2 = 5 (10% of value 1),
Total = 55
In my code this looks as follows:
var NonTrans_prices = new Array();
NonTrans_prices["NoneNon"] = 0;
NonTrans_prices["LemonNon"] = 5994;
NonTrans_prices["CustardNon"] = 7076;
function NonTrans() {
var NonTransPrice = 0;
var theForm = document.forms["GRANADANEO"];
var selectedFilling = theForm.elements["NonTrans"];
NonTransPrice = NonTrans_prices[selectedFilling.value];
return NonTransPrice;
}
var price = NonTrans_prices;
var percentage = 10;
var costs = (price * percentage) / 100;
var optionprice = price + percentage;
function optionprice1() {
var inscriptionPrice = 0;
var theForm = document.forms["GRANADANEO"];
var optionprice = theForm.elements["optionprice"];
if (optionprice.checked == true) {
inscriptionPrice = optionprice.value;
}
return inscriptionPrice;
}
function calculateTotal() {
var cakePrice = NonTrans() + optionprice1();
var divobj = document.getElementById('totalPrice');
divobj.style.display = 'block';
divobj.innerHTML = "Total Price: " + cakePrice + " \u20ac";
}
*The NonTransPrice is connected to a dropdown box, and the optionprice1 is connected to a checkbox.
As soon as I tick the checkbox containing the 10% value, the letters "on" are added to the total price. What's going wrong?
**Sorry forgot to post the entire code so that you guys/girls can test: https://jsfiddle.net/6a55tm4j/
For some reason it doesn't show the total value in jsfiddle, on the live website I am testing on it does so that's not really a problem I am facing live.
Live link: http://axesseurope.be/appalacarte/Calculator/axess_calculator.html
This is the HTML code containing the parts affected by the .js code:
<body onload='hideTotal()'>
<div id="wrap">
<form action="" id="GRANADANEO" onsubmit="return false;">
<div>
<div class="cont_order">
<fieldset>
<table><tr><td>
<label >NonTrans</label>
<select id="NonTrans" name='NonTrans' onchange="calculateTotal()">
<option value="NoneNon">Select Dimensions</option>
<option value="LemonNon">3,00 6,40 0,85</option>
<option value="CustardNon">3,00 7,50 0,85</option>
</select>
</td></tr></table>
<hr>
<br/>
<label>Granada Neo Opties Algemeen</label>
<p>
<input type="checkbox" id="optionprice" name='optionprice' onclick="calculateTotal()" />
<label for='optionprice' class="inlinelabel">optionprice</label>
</p>
<p>
<input type="checkbox" id="SchuifdeurVoorzijde" name='SchuifdeurVoorzijde' onclick="calculateTotal()" />
<label for='SchuifdeurVoorzijde' class="inlinelabel">Schuifdeur in voorzijde</label>
</p>
<div id="totalPrice"></div>
</fieldset>
</div>
</div>
</form>
In the end with the help of Scott Marcus this was the solution:
function optionprice1()
{
var chkOptionPrice = document.getElementById("optionprice");
var theForm = document.forms["GRANADANEO"];
var selectedFilling = theForm.elements["NonTrans"];
var lstNonTransValue = NonTrans_prices[selectedFilling.value];
var inscriptionPrice = 0;
if(optionprice.checked === true){
// Look up the price in the array that matches the dropdown list's value
var price = NonTrans_prices[selectedFilling.value];
// Do the math to calculate 10% of the original price
var percentage = 10;
inscriptionPrice = (price * percentage) / 100;
}
// finally we return the inscriptionPrice
return inscriptionPrice;
}
Checkboxes have a value of "on" when they are selected. Ensure that your checkboxes include a value attribute that contains the meaningful data they represent. For example:
<input type="checkbox" id="chkSomeId" name="chkSomeID"
value="someValueToBeWhenChecked">
This is true of radio buttons as well.
So, in your code, this line:
inscriptionPrice = optionprice.value
is most-likely accessing the value of either a checkbox or radio button that does not have an explicit value set for it, but is checked.
Also, remember that all values pulled from HTML come into JavaScript as strings, so if you need to do math with those values, you'll want to use parseInt() and parseFloat().
UPDATE: now that you have posted your HTML, I see this:
<input type="checkbox" id="optionprice" name='optionprice' onclick="calculateTotal()" />
which is exactly what I suspected. My above answer will correct the problem. That checkbox needs a value set for it.
UPDATE:
In your following code:
//Add percentage
var price = NonTrans_prices;
var percentage = 10;
var costs = (price * percentage) / 100;
var optionprice = price + percentage;
//Add percentage
function optionprice1()
{
var inscriptionPrice=0;
//Get a refernce to the form id="GRANADANEO"
var theForm = document.forms["GRANADANEO"];
//Get a reference to the checkbox id="optionprice"
var optionprice = theForm.elements["optionprice"];
//If they checked the box set inscriptionPrice to 20
if(optionprice.checked==true){
inscriptionPrice=optionprice.value;
}
//finally we return the inscriptionPrice
return inscriptionPrice;
}
I think that you should take the 4 var lines and include them in the function.
I think that the first line: var price = NonTrans_prices; is incorrect, because it sets the variable price to the actual array of NonTrans prices, rather than looking up a particular price, which would be:
var price = NonTrans_prices[document.getElementById("nonTransList").value];
Then, your problem is that if the optionPrice checkbox is checked, you are trying to access the value of the checkbox, which (as I've said) doesn't explicitly exist, so you get "on" (because the checkbox is checked). What you should be doing is setting the price to result of the 10% calculation that was just done on the line above. So the final function looks like this:
function optionprice1()
{
var chkOptionPrice = document.getElementById("optionprice");
var lstNonTransValue = document.getElementById(NonTrans).value;
var inscriptionPrice = 0;
if(optionprice.checked === true){
// Look up the price in the array that matches the dropdown list's value
var price = NonTrans_prices[lstNonTransValue];
// Do the math to calculate 10% of the original price
var percentage = 10;
inscriptionPrice = (price * percentage) / 100;;
}
// finally we return the inscriptionPrice
return inscriptionPrice;
}
You were close, but the thing that, I think, tripped you up was that you created a variable with the same name as your checkbox and after doing the calculation, you should have been trying to get the value of your variable, but you were trying to get the value of the checkbox, which isn't where the answer was.
I hope that I've understood what you wanted correctly, but even if my algorithm is off, I hope you can see that you don't want to be using the value of the checkbox to get your answer, since it doesn't store any value.
I have two input numbers (min and max). Is there a way to prevent user inserting values like min > max?
<input type="number" class="inputMin" placeholder="Min.">
<input type="number" class="inputMax" placeholder="Max.">
There are many different ways you can do this.
One option is whenever min is changed, if it is greater than max, change it to equal max, like this:
$('.inputMin').on('change', function() {
var max = parseFloat($('.inputMax').val());
var min = parseFloat($('.inputMin').val());
if (min > max) {
$('.inputMin').val(max);
}
});
or the opposite case when you change max:
$('.inputMax').on('change', function() {
var max = parseFloat($('.inputMax').val());
var min = parseFloat($('.inputMin').val());
if (min > max) {
$('.inputMin').val(max);
}
});
Another option is to display an error, either when the form is submitted, or dynamically as the user changes the input.
There are a number of javascript libraries that allow you to do dynamic validation very easily. Check out Angular.js, and how to use it for form validation.
Without JQuery, you can try this :
(and you have to change class to id)
var min = document.getElementById("inputMin");
var max = document.getElementById("inputMax");
function check() {
if (min.value > max.value) {
min.value = max.value;
}
};
min.addEventListener("input", check, false);
max.addEventListener("input", check, false);
You can try it there
You can use the parameters min and max like:
<form>
Quantity (between 1 and 5):
<input type="number" name="quantity" min="1" max="5">
</form>
Ref: http://www.w3schools.com/html/html_form_input_types.asp (Input Type: number)
Also you can use Javascript to check if the value is >= min_number and <= max_number, but both are client side scripts, which can be bypassen with editing the html part.
You also need a server-side check so you can be sure it's within the range.
This is an extension to this thread.
My situation:
I need a user to enter a decimal value (ie 0.05) and show a simple calculation on the fly as the user types (or pastes). The example shown works for whole numbers but not when a decimal is entered into the input field.
I need to display the result in multiple places. I assumed I could just update getElementById to getElementByClass but that didn't work.
My Code:
<input type="text" name="capname" id="numberField" value="0.07" maxlength="5" />
<span name="mpd" id="mpdresult" class="mpdresult" ></span>
<span class="mpdresult" ></span> (second display)
<script>
window.onload = function() {
var base = 500;
var numberField = document.getElementById('numberField');
numberField.onkeyup = numberField.onpaste = function() {
if(this.value.length == 0) {
document.getElementById('mpdresult').innerHTML = '';
return;
}
var number = parseInt(this.value);
if(isNaN(number)) return;
document.getElementById('mpdresult').innerHTML = number * base;
};
numberField.onkeyup(); //could just as easily have been onpaste();
};
</script>
please use
var number = parseFloat(this.value);
instead of
var number = parseInt(this.value);
use ParseFolat for Decimal Numbers
document.write(parseFloat("10.33") + "<br>");
ParseFloatSample
Use parseFloat instead of parseInt. http://jsfiddle.net/janCY/
there is no such function getElementByClass. There is getElementsByClassName, it returns array with elements. But why don't use JQuery?
I have a link which calls some javascript. The javascript populates a form value and submits it. Works fine in all browsers except internet explorer.
All other options on the page are links, thats why I also would like this option to be a link
thanks
<script type="text/javascript">
function timeZone(){
today = new Date()
difference = today.getTimezoneOffset()
var field = document.getElementById("form").timezone
alert("test")
if(difference < 0){
difference = difference * -1
field.value = "GMT+" + pad(Math.floor(difference/60), 2) + ":" + pad(difference%60, 2);
}
else{
field.value = "GMT-" + pad(Math.floor(difference/60), 2) + ":" + pad(difference%60, 2);
}
form = document.getElementById('form');
form.submit();
}
function pad(num, digits) {
num = String(num); while (num.length < digits) { num="0"+num; }; return num;
}
</script>
<form method="get" action="ViewLog.do?page=1" id="form">
<input id="timezone" name="timezone" type="hidden" value=""></input>
<img id="activityHistoryImage" Class = "navImage" src="imgs/history.png" alt="Activity history"/>
Activity history<br/>
<small class="navSubText">See your most recent activities </small>
</form>
Internet Explorer may or may not have issues with the fact that you've given an id of 'form' to your form element; I imagine it probably does. In general, it's best to avoid using tag names as the value on id or name attributes.
Also, your hidden input element has an id, yet you're not using it to reference it. Change:
var field = document.getElementById("form").timezone
to
var field = document.getElementById("timezone");
Declare variables with var.
Place ; where they should be.
I have seen a few of these jquery things going on, and just wondered if there was a simple number formatting script.
Essentially, all we wish to do, is format ( client side ) for checking purposes only, the number entered in a field. To show somewhere else on the page ( presumably in a div ) the formatted price they entered.
So lets say, field
input id="price" name="price" size="50" type="text" class="medium" /
And they enter 1234560
I want to show somewhere else on the page, :
You Entered : $1,234,560.00 as the price. Is this correct ?
This is only for visual purposes only. Alternatively, changing the value of what they type and formatting it "live" could be an option, however the value we want to send to the db is pure numerics, ie: 1234560
Setup a function like this one
Javascript format currency
function CurrencyFormatted(amount) {
var i = parseFloat(amount);
if(isNaN(i)) { i = 0.00; }
var minus = '';
if(i < 0) { minus = '-'; }
i = Math.abs(i);
i = parseInt((i + .005) * 100);
i = i / 100;
s = new String(i);
if(s.indexOf('.') < 0) { s += '.00'; }
if(s.indexOf('.') == (s.length - 2)) { s += '0'; }
s = minus + s;
return s;
}
Then set an onchange for jQuery something like this
jQuery(document).ready(function(){
jQuery('#price').change(function(){
jQuery('#mydivsomewhere').val(CurrencyChange(jQuery('#price').val()));
});
});
Not sure if that is 100% correct, haven't tested it. But should call CurrencyFormat whenever the text in your input box changes. Should pass in the val of the textbox with id of price and set a div of id mydivsomewhere with the formatted value.