Changing an Object property value via mathematical expression in javascript - 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);

Related

Subtract amount on form submit JavaScript / JQuery

I have a checkout page, where I would like to implement a new feature: subtract from total cart value a certain amount, introduced in an input.
Example: There is 1 item in cart, with value of 10.00$. If user typed 100 in that input, then he would have a discount of 1$ (100 pts = 1$ in this example) and the final value of the cart would be 9.00$. Since I'm using some integrated apps for getting/calculating item value, total cart value, etc. I would like to get some generic code, which I would eventually adjust, to link with my existing code, functions, etc.
The function I have should have these features:
create form
get input value
subtract used points from user's total amount (for example totalPts = 1000)
subtract from cart total value used points, converted into $ (100pts = 1$)
For now, my function looks like this:
function appendRefferalPoints() {
const totalPts = 1000;
// creating form - ok
$form = $('<form id="refForm" class="coupon-form" action></form>');
$form.append(
'<input type="text" id="refValue" name="refInput" class="coupon-value input-small" >'
);
$form.append('<button type="submit" class="btn">Aplica</button>');
$("body").append($form);
// get input value - not ok
$("#refForm").submit(function () {
let value = 0;
$.each($("#refForm").serializeArray(), function (i, field) {
value[field.name] = field.value;
});
});
// subtraction from totalPts logic - not ok
let rez = totalPts - value;
console.log("Final Rez: " + rez);
// subtraction converted pts from cart value logic
}
Now when I submit the form I only url changes from /checkout#/cart to /checkout/?refInput=512#/cart
function appendRefferalPoints() {
const totalPts = 1000;
let cartValue=10;
let discount=0;
let inputValue = 0;
// creating form - ok
$form = $('<form id="refForm" class="refForm coupon-form" ></form>');
$form.append(
'<input type="text" id="refValue" name="refInput" class="coupon-value input-small" value="100" >'
);
$form.append('<button id="btnClick" class="btn">Aplica</button>');
$("body").append($form);
$(document).on("submit", "#refForm", function(e){
//getting input value while submitting form
inputValue=$("#refValue").val();
//converting 100 pts to 1 dallor
discount=inputValue/100;
//calculating balance pts
let balancePts = totalPts - parseInt(inputValue);
//calculating final amount
let finalCartValue=cartValue-discount;
alert("finalCartValue"+finalCartValue);
});
}
appendRefferalPoints();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

HTML value as input for Javascript Function and Return the Output back to HTML

I`ve been trying to create a function that (1) uses data input from the HTML to make the calculation and (2) return the result back to the HTML.
I am having some trouble finding the mistake, if you could please help me I'd be glad.
<!DOCTYPE html>
<html>
<body>
<h2>Celcius to Fahrenheit</h2>
<input type="number" id="input-temperature"></input>
<p id="calc-result"></p>
<script>
function toCelsius() {
var x = document.getElementbyId("input-temperature").value;
return (5/9) * (x-32);
}
document.getElementById("calc-result").innerHTML = ("The result is" + toCelsius());
</script>
</body>
</html>
It looks like you made some minor mistakes:
getElementById instead of getElementbyId
You'll need to update the value every time the input field changes: addEventListener('keyup', function() {...})
You have the calculation in reverse: 9 / 5 * x + 32
This is my complete code:
document.addEventListener('DOMContentLoaded', function() {
document.getElementById("input-temperature").addEventListener('keyup', onInputChanged);
})
function toCelsius() {
var x = document.getElementById("input-temperature").value;
return 9 / 5 * x + 32;
}
function onInputChanged() {
document.getElementById("calc-result").innerHTML = "The result is " + toCelsius();
}
See this codepen: https://codepen.io/bertyhell/pen/WZQQgZ?editors=1011
You misspelled getElementbyId. It should be getElementById (capital B).
To calculate and display celcius, you can create a button and on click of the button call toCelcius function (as below).
I have made the following changes in the function:
Checking whether the value entered is blank using if (x != "").
function toCelsius() {
var x = document.getElementById("input-temperature").value;
var Celcius = 0;
if ( x != "") Celcius = (5 / 9) * (x - 32);
document.getElementById("calc-result").innerHTML = ("The result is " + Celcius);
}
<input type="number" id="input-temperature"></input>
<p id="calc-result"></p>
<button id="btnCalculate" onclick="toCelsius()">Calculate</button>

Issues with javascript using html inputs as variables (Beginner!)

Hello Everyone!
Im having some issues with a simple calculator type website. My issue involves using a javascript function to calculate an equation using variables from an HTML input form.
Below is my javascript function, which is placed above the form in the HTML file.
var userName = document.getElementsByName("userName")[0].value;
var userMmr = document.getElementsByName("userMmr")[0].value;
var userDesmmr = document.getElementsByName("userDesmmr")[0].value;
var userWinrate = document.getElementsByName("userWinrate")[0].value;
function findshit(){
alert(userMmr.value);
var LR = 1.0 - userWinrate.value;
var GP = 1;
while (1){
var GW = GP * userWinrate.value;
var GL = GP * LR;
var MMRG = GW * 25;
var MMRL = GL * 25;
var TMG = MMRG - MMRL;
if (TMG + userMmr.value >= userDesmmr.value) {
alert("Congrats! it will take you " + String(GP));
} else {
GP += 1;
}
}
}
<h2>Enter your information below</h2>
</br>
<form>
What's your name?:<br>
<input type="text" name="userName" onkeyup="findshit();" onchange="findshit();"/><br>
</br>
What's your current mmr?:<br>
<input type="text" name="userMmr" onkeyup="findshit();" onchange="findshit();"/><br>
</br>
What's your desired mmr?:<br>
<input type="text" name="userDesmmr" onkeyup="findshit();" onchange="findshit();"/><br>
</br>
What's your current win rate?<br>(put in decimal form eg. 50% = .50):<br>
<input type="text" name="userWinrate" onkeyup="findshit();" onchange="findshit();"/"><br>
<br>
<button onclick="findshit();">Try it</button>
Don't use .value when you set all the variables at the top. The code in the function expects those variables to just be the elements, because it uses .value to get their updated values. So it should just be:
var userName = document.getElementsByName("userName")[0];
var userMmr = document.getElementsByName("userMmr")[0];
var userDesmmr = document.getElementsByName("userDesmmr")[0];
var userWinrate = document.getElementsByName("userWinrate")[0];
You also need to put the script after the HTML, or put all the code inside the window.onload function. If you run the script before the HTML is loaded, none of the document.getElementsByName() calls will find the elements.
You should remove or modify while (1) loop. Because it is an infinite loop. I think you should use If loop in the scenario.

Getting values from list<String> , split them and then slice them by parts, using JavaScript

I have List<String> from Spring MVC which i want to split, slice and print on browser. The problem is that i need to enter a start and end argument of slice() method as a variable from text-field. This is my code, but it doesn't work. Can someone helps me with that? This is my code:
<body>
<form>First value:
<br/>
<input type="text" id="firstvalue" />Last value:
<br/>
<input type="text" id="lastvalue" />
<button onclick="myFunction()">Press</button>
<p id="demos"></p>
</form>
<script>
function myFunction() {
var str = "${first}";
var arr = str.split(",");
var first = document.getElementById('firstvalue');
var second = document.getElementById('lastvalue');
document.getElementById("demos").innerHTML = arr.slice('first', 'second');
}
</script>
</body>
Thank you in advance!
you got some issues in your code.
if ${first} is List<String>, then you need to convert it to a concatenated single comma separated String. Because by ${first} you are just printing list object.
slice expects index which is number, you are passing String
You are not doing .value after document.getElementById
You are not passing the user input variables first and second to slice, Instead you are passing hardcoded strings 'first' and 'second'.
Below is the fixed code
HTML
<form>First value:
<br/>
<input type="text" id="firstvalue" />Last value:
<br/>
<input type="text" id="lastvalue" />
<button onclick="myFunction(event)">Press</button>
<p id="demos"></p>
</form>
JS
var myFunction = function (e) {
var str = "${first}" // assuming this contains string like "1,2,3,4,5,6,7,8,9,10"; and not the List obect
var arr = str.split(",");
var first = document.getElementById('firstvalue').value;
var second = document.getElementById('lastvalue').value;
document.getElementById("demos").innerHTML = arr.slice(parseInt(first, 10), parseInt(second, 10)).toString();
e.preventDefault();
};
What do we want to achieve?
We have two input textfields: one holding a start value and one holding an end value. On a click we want to create a range from the start to the end value and output it into a container.
Solution
The solution is more simple than expected and we do not require split, slice and part. Also we do not really require a predefined list holding all values.
Example
<html>
<head>
<script>
function evalRange(){
var tS = parseInt(document.querySelector('#inFrom').value); //Our start value;
var tE = parseInt(document.querySelector('#inTo').value); //Our end value;
var tR = document.querySelector('#demos'); //Our output div
if (tE >= tS){
//We are using the Array.apply prototype to create a range
var tL = Array.apply(null, Array(tE - tS + 1)).map(function (a, i){return tS + i});
//We output the range into the demos div
tR.innerHTML = tL.join(',')
}
else tR.innerHTML = 'To has to be higher than from';
//Returning the range list
return tL
}
</script>
</head>
<body>
<input type = 'text' id = 'inFrom' value = '10' />
<input type = 'text' id = 'inTo' value = '20' />
<b onclick = 'evalRange()'>Range</b>
<div id = 'demos'></div>
</body>
</html>
And here is a fiddle for it: https://jsfiddle.net/91v3jg66/

Math.floor() and parseFloat() clash?

$('#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.

Categories

Resources