Math.floor() and parseFloat() clash? - javascript

$('#pm').val(Math.floor(parseFloat(pm*100/100)));
Full code:
<script type="text/javascript">
function updatePay() {
// Grab all the value just incase they're needed.
var current_price = <?php echo json_encode($current_price); ?>;
var pm = $('#pm').val();
var gg = pm/current_price;
// Set the new input values.
$('#pm').val(Math.floor(parseFloat(pm*100/100)));
$('#gg').val(gg);
}
$('#pm').keyup(updatePay);
$('#gg').keyup(updatePay);
</script>
When I use Math.floor it doesn't allow me to enter a second decimal.
I need my code to be able to allow a second decimal place to be filled in, how can I do this in Javascript?

Try this
$('#pm').val((Math.floor(parseFloat(pm)*100)/100).toFixed(2));
I think you want to round down and allow 2 decimal places,
so if the number is 3546.699433
parseFloat(pm)*100 = 354669.9433
math.floor(354669.9433) = 354669
354669/100 = 3546.69
<script type="text/javascript">
function updatePay() {
// Grab all the value just incase they're needed.
var current_price = <?php echo json_encode($current_price); ?>;
var pm = $('#pm').val();
var gg = pm/current_price;
// Set the new input values.
$('#pm').val((Math.floor(parseFloat(pm)*100)/100).toFixed(2));
$('#gg').val(gg);
}
$('#pm').change(updatePay);
$('#gg').chnage(updatePay);
</script>
If you want something that gets updated on keyup, try something along these lines
Javascript:
document.getElementById("num1").onkeyup = function(){
var val = (Math.floor(parseFloat( document.getElementById("num1").value)*100)/100).toFixed(2);
if(isNaN(val)){
document.getElementById("result").innerHTML = "pm will appear here";
}
else if(val){
document.getElementById("result").innerHTML = val;
} else {
document.getElementById("result").innerHTML = "pm will appear here";
}
}
HTML:
<body>
<input type="button" id="myButton" value="click me"/>
<span id="result"></span>
<input type="text" id="num1" value="1.1111"></div>
</body>

It's hard to tell what you're trying to achieve, but at a guess I suspect you want the values displayed in pm and gg to have two digits of fractional precision. If so:
function updatePay() {
// Grab all the value just incase they're needed.
var current_price = <?php echo json_encode($current_price); ?>;
var pm = parseFloat($('#pm').val()); // Parse here
var gg = pm/current_price;
// Set the new input values.
$('#pm').val(pm.toFixed(2)); // Round to two places and turn back into text
$('#gg').val(gg.toFixed(2)); // " " " " " " " " "
}
Side note: You have this set as a keyup handler on the gg element, but you're always overwriting what the gg element has in it, without using the value in gg at all. If I were a user, I'd find that pretty irritating.

Related

Javascript, dynamic color HTML inputbox if value insert is included in range

Good Afternoon,
I need to check if the value insert by the user inside an inputbox on my PHP page it's included in specific range. So if the value insert isn't included in this range i need to color the text in the inputbox or show a message. The range is definited from two PHP variables.
For example if my range will be >10 and <20 any number from 11 to 19 will be 'ok' and any another number (out of this range) will be colored in red or something like this.
I tried to use something like this:
<script>
function checkFilled() {
var inputVal = document.getElementById("myinputbox");
var min = "<?php echo $someVar2; ?>";
var max = "<?php echo $someVar3; ?>";
if (inputVal.value < min) {
inputVal.style.backgroundColor = "yellow";
}
else if (inputVal.value > max) {
inputVal.style.backgroundColor = "yellow";
}
else {
inputVal.style.backgroundColor = "";
}
}
checkFilled();
</script>
PHP:
$someVar2 = 10;
$someVar3 = 20;
echo '<input type="text" id="myinputbox" onchange="checkFilled();">';
This way doesn't work and all number I insert in my inputbox will be change the color to yellow. If I try to set the min and the max variable with a number directly in Javascript (without reading the variable from PHP) the script work.
Could anyone please help me?
Thanks you very much for your help.
Regards
Good Afternoon
you can go this way
<input type="text" id="myinputbox" oninput="myFunction()">
<script>
function myFunction() {
var inputVal = document.getElementById("myinputbox").value;
var min = "<?php echo $someVar2; ?>";
var max = "<?php echo $someVar3; ?>";
if (inputVal.value < min) {
document.getElementById("myinputbox").style.backgroundColor = "yellow";
}
else if (inputVal.value > max) {
document.getElementById("myinputbox").style.backgroundColor = "red";
}
else {
document.getElementById("myinputbox").style.backgroundColor = "";
}
}
</script>
you have to use oninput event and try debugging you will get it
All the best

NaN return from JavaScript function while alert is returning number

I want to show word output of a currency number as tool tip. I want to achieve something like this -> on hover get the value inside table, calculate word equivalent and display it as tool tip.
I am using Number to word converter function which is working fine independently. But the below code is returning Not a number although "var b" alerts to a numeric value.
function getVal() {
$('#data1 tr td.num').hover(function() {
var a = $(this).html();
var b = parseFloat(a.replace(/[^0-9.]/g, ''));
alert(b); /// working fine giving number as alert
return parseInt(b, 10);
});
}
/****setting title function ***/
function titleSetter(node) {
var num2words = new NumberToWords();
num2words.setMode("indian");
var indian = num2words.numberToWords(getVal()); /// NaN error
return indian;
}
/****setting title value ***/
$('.num').tooltip({
title: titleSetter
})
<td class="text-right num" data-toggle="tooltip"><i class="fa fa-inr"></i>
<?php echo $fmt ->format($sum); ?></td>
Some help to this code or something else fulfilling my requirement is a welcome and thanks in advance
The issue is that getVal function is adding a hover event, which is not returning any value.
Try passing in the text from titleSetter to getVal like this:-
function getVal(text) {
var b = parseFloat(text.replace(/[^0-9.]/g, ''));
alert(b); /// working fine giving number as alert
return parseInt(b, 10);
}
/****setting title function ***/
function titleSetter() {
var num2words = new NumberToWords();
num2words.setMode("indian");
var text = $.trim($(this).text());
var indian = num2words.numberToWords(getVal(text));
return indian;
}
/****setting title value ***/
$('.num').tooltip({
title: titleSetter
})

making a calculation using JavaScript

Why this isn't working?
I also did this by assigning the result back to the input field but that didn't work and still this is not showing an alert which should show the result..
<script type="text/javascript">
function calculate() {
var calculateit=document.getElementById('disp');
var pluscharacter=/+/;
var matchplus=calculateit.search(pluscharacter);
var inputlength=calculateit.length;
if(matchplus!=-1 && matchplus!=0 matchplus!=inputlength) {
answer=calculateit[0]+calculateit[1];
alert("Your answer is: "+answer+" Is it?");
}
}
</script>
Your if statement isn't a valid condition. Try:
if(matchplus!=-1 && matchplus!=0 && matchplus!=inputlength)
var calculateit = document.getElementById('disp');
var matchplus = calculateit.search(pluscharacter);
calculateit is a Node doesn't have any search() method.
You're doing stuff you don't need to do - just split the string. You also need to get the innerHTML - THAT's the string. Or you can get the "value" from an input field instead. I'd trim it to get rid of the white space around the equation, though the parseInt would take care of that as well. I'd also push the answer into another div. Here's a jsfiddle:
https://jsfiddle.net/mckinleymedia/9ezky35v/2/
With this HTML:
<h3>Equation</h3>
<div id="disp">12+12</div>
<h3>Answer</h3>
<div id="answer"></div>
You can use this script:
function calculate() {
var calculateit = document.getElementById('disp').innerHTML.trim(),
numbers = calculateit.split('+'),
answerDiv = document.getElementById('answer');
if ( numbers.length > 1 ) {
answer = parseInt(numbers[0]) + parseInt(numbers[1]);
answerDiv.innerHTML = "Your answer is: <b>" + answer + "</b>, Right?";
} else {
answerDiv.innerHTML = "I can't calculate that equation.";
}
}
calculate();

Changing an Object property value via mathematical expression in javascript

I'm trying to change the value of a property through a function method. I have it working but not exactly how i need it to work. Right now based of of user input it adds the number to value of speed. But not in a mathematical way. Instead it just adds it to the end of the value. so instead of doing 12 + 2 and getting 14. I get 122. How do i get it to add the values together?
HTML
<form>
<input type="number" id="speed" min="-6" max="15" required>
<input type="button" id="gear_submit" value="Submit" onclick="createBike();">
</form>
<p id="show_speed"></p>
Javascript
function createBike(){
function bike(model, speed){
this.model = model;
this.speed = speed;
// this will change speed based on user input
this.changeSpeed = function (changeSpeed) {
var new_speed = document.getElementById("speed").value;
if (new_speed > 0 ){
bikeArray[0].speed = speed + new_speed;
}
else if (new_speed < 0 ){
bikeArray[0].speed - speed - new_speed;
}
}
}
var bike1 = new bike("Ghost Ryder", "12");
bikeArray[0] = bike1;
bike1.changeSpeed();
document.getElementById("show_speed").innerHTML = bikeArray[0].model + " " + bikeArray[0].speed;
}
It's treating your numbers as strings, and concatenating the strings instead of adding the numbers. To fix this you need to first remove the quotes around the number in your constructor so that it's a number and not a string, and secondly you need to use parseInt on the value that comes from your speed input element.
Working Example:
var bikeArray = [];
function createBike() {
function bike(model, speed) {
this.model = model;
this.speed = speed;
// this will change speed based on user input
this.changeSpeed = function(changeSpeed) {
/* The value on the following line gets parsed using parseInt */
var new_speed = parseInt(document.getElementById("speed").value, 10);
bikeArray[0].speed = speed + new_speed;
}
}
/* The object gets initialized using an integer value here instead of a string */
var bike1 = new bike("Ghost Ryder", 12);
bikeArray[0] = bike1;
bike1.changeSpeed();
document.getElementById("show_speed").innerHTML = bikeArray[0].model + " " + bikeArray[0].speed;
}
<form>
<input type="number" id="speed" min="-6" max="15" required>
<input type="button" id="gear_submit" value="Submit" onclick="createBike();">
</form>
<p id="show_speed"></p>
JSFiddle Version: https://jsfiddle.net/a453bngn/2/
You need to read the variable as a number, not a string. parseInt() does this.
bikeArray[0].speed = parseInt(speed, 10) + parseInt(new_speed, 10);

Jquery, get label value inside a user control

I need to make a calculation in an asp.net page with the value from a usercontrol label.
the user control label is:
<asp:Label ID="LblInvoicePriceValue" runat="server" ></asp:Label>
I include it like this:
<Controls:VehicleInformation ID="VehicleInformationControl" runat="server" />
And my jquery function is something like:
Please see point 1 and 2.
<script type="text/javascript">
$(document).ready(function () {
alert('call function to do calculation here');
// 1. Find in the vehicle information user control the invoiced ammount label
// 2. Find the vat excluded value **after** it was typed in the textbox
// 3. If invoiced ammount is greater than zero, then
// 3.a Find Label Percentage
// 3.b Label.Text = (AmmountWithoutVat/InvoicedAmmount)*100 + '%'
});
</script>
HTML generated:UPdate1
For the label:
<span id="MainContent_VehicleInformationControl_LblInvoicePriceValue" class="bold"></span>
For the textbox:
<input name="ctl00$MainContent$TxtVatExcluded" type="text" id="TxtVatExcluded" class="calculation" />
Update 2:
<script type="text/javascript">
$(document).ready(function () {
alert('call function to do calculation here');
$("#TxtVatExcluded").keypress(function() {
var invoiceprice = $("#MainContent_VehicleInformationControl_LblInvoicePriceValue").text();
var vatexcluced = $("#TxtVatExcluded").val();
var lblPercentage = $("#MainContent_LblPercentage");
if (invoiceprice > 0) {
lblPercentage.text((vatexcluced / invoiceprice) * 100);
}
})
// 1. Find in the vehicle information user control the invoiced ammount label
// 2. Find the vat excluded value after it was typed in the textbox
// 3. If invoiced ammount is greater than zero, then
// 3.a Find Label Percentage
// 3.b Label.Text = (AmmountWithoutVat/InvoicedAmmount)*100 + '%'
});
</script>
var label_text = $("#MainContent_VehicleInformationControl_LblInvoicePriceValue").text();
$("#TxtVatExcluded").val(label_text);
UPDATE
If you want to check if the textfield is blank then only do copy the label then use following code
var label_text = $("#MainContent_VehicleInformationControl_LblInvoicePriceValue").text();
var txt = $("#TxtVatExcluded").val();
if(txt.length==0)
{
$("#TxtVatExcluded").val(label_text);
}
You can use the rendered ID of the elements to get the values using jQuery
var lbl = $("#MainContent_VehicleInformationControl_LblInvoicePriceValue").text();
var tbox = $("#TxtVatExcluded").val();
Later when the calculation is complet, you can update the label text as
$("#MainContent_VehicleInformationControl_LblInvoicePriceValue").html("new label");
Update:
To use the logic, where the user types, you have to bind the function to keypress/keyup/keydown event
$("#myinputbox").keypress(function() {
var lbl = $("#MainContent_VehicleInformationControl_LblInvoicePriceValue").text();
var tbox = $("#TxtVatExcluded").val();
//... so on
}
Update 2:
Since, you are attempting to calculate with the values, it is safer to make sure, there are numbers in the first place. For that, you can use parseInt(), parseFloat() as needed.
$("#TxtVatExcluded").keypress(function() {
var invoiceprice = $("#MainContent_VehicleInformationControl_LblInvoicePriceValue").text();
var vatexcluced = $("#TxtVatExcluded").val();
var lblPercentage = $("#MainContent_LblPercentage");
if (invoiceprice > 0) {
lblPercentage.text((parseInt(vatexcluced) / parseInt(invoiceprice)) * 100);
}
})
This will get you the value of the label control:
function Calculate()
{
var InvoicedAmmount = $("#MainContent_VehicleInformationControl_LblInvoicePriceValue").text();
var AmmountWithoutVat = $("#TxtVatExcluded").val();
var Result = (AmmountWithoutVat/InvoicedAmmount)*100
$("#OutputLabel").html(Result + " %");
}
You can attach and onBlur event to your text box to fire your calculation when they leave the text box - you wouldn't really want to re-calculate the amount as they typed.
$(document).ready(function ()
{
$("#TxtVatExcluded").bind("blur",function(){ Calculate(); });
}

Categories

Resources