Changing Javascript variable value after onclick action - javascript

Pretty new to this Javascript thing.
I want to change a Javascript variable when a user inserts a number into an input field in my HTML document and clicks a button.
I'm assuming you'd use a function, but how do you gather the data and change the variable?
The stuff I tried to make looks a little something like this.
HTML
<input type="number" id="inputField">
<button onclick="changeTheVariable()" type="button" id="pushMe"></button>
Javascript
var a = 0;
function changeTheVariable() {
a = document.getElementById("inputField").value;
}
but it's not working!
Edit 1:
Wow. I didn't think I'd get this kind of attention. I also found it a bit strange it didn't work at first.
The question I'm asking is partly for a calculator here: https://titomagic.com/debug
It's simple, you type in a number, click the button and it calculates (based on other variables) to a result on the bottom.
Here's a link to the Javascript file, if you wanna have a look: https://titomagic.com/js/bursdagskalkulator.js
To those of you asking; yes, I've been testing with a console.log and the variable is not changing. It's not affecting the other variables (as it should?).
Also I've never heard of JSfiddle.

I discovered few things in the summarizeGjester() function. First of all I moved all the Javascript code in the bursdagskalkulator.js file inside the summarizeGjester() function. Also I converted var antallGjester to integer using parseInt() function, because it was treated as string before.
var antallGjester = document.getElementById("gjesterAntallInput").value;
antallGjester = parseInt(antallGjester); //integer conversion
Also the first Boolean comparison was changed to
if ((antallGjester < 10) && (antallGjester > 0)), so that the second one would work if there’s 0 value: else if (antallGjester === 0).
function summarizeGjester() {
var antallGjester = document.getElementById("gjesterAntallInput").value;
antallGjester = parseInt(antallGjester);
var fastPris = 1500;
var fastPrisDifferanse = 10;
var gjestePris = 120;
var gjesteDifferanse = antallGjester - fastPrisDifferanse;
var gjesteSum = gjestePris * gjesteDifferanse;
var gjesterTotalt = 0;
if ((antallGjester < 10) && (antallGjester > 0)) {
console.log("antallGjester < 10");
gjesterTotalt = 1500;
} else if (antallGjester === 0) {
console.log("antallGjester === 0");
gjesterTotalt = 0;
} else {
console.log("else");
gjesterTotalt = fastPris + gjesteSum;
}
document.querySelector('#results').innerHTML = gjesterTotalt;
}
<form>
<div class="form-group">
<label for="gjesterAntall">Antall barn:</label>
<input type="number" class="form-control" id="gjesterAntallInput">
</div>
<button class="btn btn-lg btn-warning" onclick="summarizeGjester()" type="button" id="sumGjester">Legg sammen</button>
</form>
<h1 class="text-center" style="font-size:80px;"><strong><span id="results">0</span>,-</h1>
I hope this helps :-)

HTML
<input type="number" id="inputField" ClientIDMode="static">
<button onclick="changeTheVariable()" type="button" id="pushMe"></button>
Javascript
var a = 0;
function changeTheVariable() {
a = document.getElementById('inputField').value;
alert(a);
}
Use Static ClientIDMode for stable id and access after page rendering
PlaceHolders canh change childe's id

I suppose this will work for you
var a = 0;
function changeTheVariable() {
a = document.getElementById("inputField").value || a;
document.getElementById("result").innerText = parseFloat(a);
}
<input type="number" id="inputField">
<button onclick="changeTheVariable()" type="button" id="pushMe">Click me</button>
<div>Result: <span id="result"></span></div>
Edited:
The reason behind this code is not running in jsfiddle is here.
After making the changeTheVariable() global variable this code will work in jsfiddle also. Here https://jsfiddle.net/1b9cfmje/
Use the following javascript code:
window.onload = function(){ var a = 0; window.changeTheVariable = function() { a = document.getElementById("inputField").value || a; document.getElementById("result").innerText = parseFloat(a); }}

Related

How to make a text appear with a desired innerHTML using javascript/jquery

There is a button and a h2 tag. the h2 tag has its visibilty=hidden.
When the button is clicked, I want to call a function that calculates the cost and changes the innerHTML of h2 accordingly and then changes its visibility=visible.
HTML:
<main class="form-signin">
<form>
<div class="card">
<label for="inputAdult">Enter number of adults</label><input type="number" id="inputAdult" class="form-control" placeholder="No. of adults" required>
<label for="inputChildren">Enter number of children (4-12yo)</label><input type="number" id="inputChildren" class="form-control" placeholder="No. of children" required>
<button type="button" onclick="showCost()" id="btn3">Calculate my cost</button>
<h2 class="changeCost">Your total cost: $0</h2>
</div>
</form>
</main>
JavaScript / jQuery :
$("h2").css("visibility","hidden");
function calculateCost(){
var a = $("#inputAdult").val();
var c = $("#inputchildren").val();
if (((a+c)%3==0)||((a+c)%3==1)) {
var rooms = (a+c)/3;
}
else {
var rooms = ((a+c)/3)+1;
}
var cost = rooms*300;
return cost;
}
function showCost() {
var display = "Your total cost is: $" + calculateCost();
var x = $("h2");
x.value = display;
$("h2").css("visibility","visible");
}
Try x.text(display) instead of setting value. That changes the innerText of the element. If you'd like to set its HTML content, use x.html(display).
The value accessor is used for plain HTMLElement objects, not for jQuery-wrapped objects.
Apart from this, you should never access a tag solely by its tag name. Always give it some kind of class name or ID. You already gave it the changeCost class, so you could do $("h2.changeCost") rather than $("h2").
To avoid getting NaN do the following:
Javascript is case sensitive so replace line
var c = $("#inputchildren").val();
with
var c = $("#inputChildren").val();
I would also consider declaring rooms variable from if and else scope so it is accessible on calculations: see full function bellow:
function calculateCost(){
var a = $("#inputAdult").val();
var c = $("#inputChildren").val();
var rooms = 0;
if (((a+c)%3==0)||((a+c)%3==1)) {
rooms = (a+c)/3;
}
else {
rooms = ((a+c)/3)+1;
}
var cost = rooms*300;
return cost;
}

How to use DOM referenced .value's in different scopes? (refactoring/scope issue)

Thanks for stopping by! I have a piece of working code here at JSFiddle
It's a basic sort of a calculator that takes 4 values, runs them through a function and spits out the result. It works as expected until I try to refactor the code. As soon as I try to refactor it at least like this, which gives me NaN or 0 whatever I do.
Here's the original code itself
<!DOCTYPE html>
<html>
<body>
See how rich you can get just flipping stuff
<input type="number" id="bp" placeholder="Buying price">
<input type="number" id="n" placeholder="Amount">
<input type="number" id="sp" placeholder="Selling price">
<input type="number" id="t" placeholder="Tax % (1 by def, 3 prem)">
<button id="button" onclick="profit()">Get rich!</button>
<input type="text" id="r" placeholder="Profit (unless ganked)">
<button id="button" onclick="resetOnClick()">More!</button><br>
<p>Thank HumbleOldMan later, go get rich now.</p>
var profit = function(){
var bp = document.getElementById("bp").value;
var n = document.getElementById("n").value;
var sp = document.getElementById("sp").value;
var t = document.getElementById("t").value;
var result = Math.floor((sp*n-(sp*n/100)*t)-bp*n)
console.log(result);
document.getElementById("r").value = result;
}
var resetOnClick = function(){
document.getElementById("t").value =
document.getElementById("sp").value =
document.getElementById("n").value =
document.getElementById("bp").value = "";
console.log("reset clicked");
}
// just couldn't use assigned variables for DOM references for a reason. Must be scope bs or I'm just a noob//
And here is what I tried doing
<script type="text/javascript">
var bp = Number(document.getElementById("bp").value);
var n = Number(document.getElementById("n").value);
var sp = Number(document.getElementById("sp").value);
var t = Number(document.getElementById("t").value);
var r = Number(document.getElementById("r").value);
var result;
var calcProfit = function(bp,n,sp,t,r){
var result = Math.floor((sp*n-(sp*n/100)*t)-bp*n)
console.log(Number(result));
r = Number(result);
}
var resetOnClick = function(){
document.getElementById("t").value =
document.getElementById("sp").value =
document.getElementById("n").value =
document.getElementById("bp").value = "";
console.log("reset clicked");
}
</script>
The question is common. What am I doing wrong? I definitely don't wont to settle for the fist version and get used to doing things just like that. Any assistance will be highly appreciated.
You've to get the value of input fields while after click, not on page load which will give value to NaN because initially all are empty. Get inside the calcProfit function so you'll get updated values.

ASP.Net MVC Javascript Keyboard not working

My virtual keyboard was working but when I added the button inside a Form instead of a Div it stopped working.
This is my javascript code:
$(document).ready(function () {
function input(e) {
//var u = document.rateformular;// duplicated with f and not used
var f = document.rateformular;
var b = f.elements["ratezeichen"];
var zeichen = b.value;
zeichen.value = zeichen.value + e.value
}
And the button has this onclick:
<div class="cities">
<input id="btn1" type="button" value="a" class="btn btn-default" onclick="input(this);" />
</div>
your input function has to be declared in the global scope
outside $(document).ready(function () {...
or
directly attached to global object window.input = function(e) { ...
This is what I did to fix my problem.
function input(e) {
var f = document.rateformular;
var b = f.elements["ratezeichen"];
if (b.value == 0) {
b.value = b.value + e.value;
}
else {
}
The main problem was in the scope and then I had to make a few changes in the code.
Thanks StackOverFlow.
The if cicle is to prevent that the user can input 2 letters, they only can type 1 letter, it's the max lenght of the TextBox, it's part of my application.

A function that is not a function?

I'm still new to coding and I'm trying to make a cookie clicker type game. I get
upgradecursor is not a function
when I run it on Chrome. I don't really understand the problem as I have a function called upgradecursor.
Pls help! :(
<!DOCTYPE html>
<html>
<head>
<title> Test </title>
<script>
//List of variables
var cookie = 0;
var cursor = 1;
var cursorupgradecost = 10;
function addcookie(){
var textField = document.getElementById( "textField" );
var currentValue = parseInt(textField.value);
cookie = cookie + cursor;
// Add one
currentValue = currentValue + cursor;
// Put it back with the new +1'd value
textField.value = currentValue;}
function upgradecursor(){
var textField = document.getElementById( "textField" );
var currentValue = parseInt(textField.value);
cookie = cookie - cursorupgradecost;
// Minus one
currentValue = currentValue - cursorupgradecost;
// Put it back with the new -10'd value
textField.value = currentValue;
//change the cost of the upgrade
cursorupgradecost = cursorupgradecost * 1.5;
//Upgrade the cursor
cursor = cursor + 1;
}
</script>
</head>
<body>
<script>
if (cursorupgradecost > cookie){
upgradecursor = false;}
else{
upgradecursor = true;}
</script>
<button type ="button" onClick = "upgradecursor()"/>Upgrade Cursor </button>
<input type="text" value="0" disabled name="lvl">
<br>
<button type="button" onClick="addcookie()"/>Add Cookie</button>
<input type="button" value="Cookies" disabled name="clicker">
<input type="text" value="0" id="textField" readonly/>
</body>
</html>
You are overwriting upgradecursor with a global variable after you include the JavaScript.
<script>
if (cursorupgradecost > cookie) {
upgradecursor = false;
} else {
upgradecursor = true;
}
</script>
This is the offending code. You need to rename this variable to something else to avoid overwriting the function.
Additionally, you should definitely avoid declaring global variables like this and look at making your code more encapsulated/modular.
--
Update based on your objective: If you want to only upgrade the cursor given a certain use case, then it might be useful to have a specific click handler that will run this check inside itself before calling upgradecursor. For example: -
function onCursorClick() {
if (cursorCost > cookie) {
// do something
} else {
upgradeCursor();
}
}
Notice how I have used camel casing to declare my functions and variables? Make sure you update your variable declarations to match my casing. This is common practice. You can read more on coding conventions here: W3Schools JavaScript Style Guide
I'd like to point out listeners should be attached via JavaScript (see DOM Event Listeners), but make sure you update the click handler to match our update, like so: -
<button type="button" onClick="onCursorClick()"/>Upgrade Cursor</button>
You have this:
if (cursorupgradecost > cookie){
upgradecursor = false;}
else{
upgradecursor = true;}
So while you started out by defining upgradecursor as a function, you overwrote it with a boolean before you ever called it.
The problem is here:
<script>
if (cursorupgradecost > cookie){
upgradecursor = false;}
else{
upgradecursor = true;}
</script>
What on earth is that supposed to even do?
Remove it and it should work.

how to store input box number in jQuery

Imagine how a normal calculator do. Use click button to input the data in a display box. Now i want to click a button to show "+" and also remove all the number in display but store it. So I can click to show the new number. After that, store those data include number1, "+" and number 2. For example: ("1","+" "2"). The reason of doing that but not using javascript for normal calculating is because I want to use Ajax to send to php and use php to execute the maths.However, I get stuck in this part.
var memory = "";
$("#add").click(function() {
memory += $show.val() + "+";
if($show.val().length >= 1){
$show.val("+");
} else {
$show.val("");
}
}
[Obligatory warning against evaluated code from a string on a server]
I would recommend trying to get a working version of your project using only javascript before trying more advanced concepts.
var memory = [];
$("#add").click(function() {
var val = $show.val();
if (val)
memory.push(val);
$show.val('+');
});
$('#submit').click(function () {
var s = memory.join('+');
memory = [];
$.get(...
});
Check Fiddle here
var one = $("#one");
var two = $("#two");
var add = $("#add");
var show = $("#show");
var equal = $("#equal");
var memory = "";
one.click(function(){
memory += "1";
show.val("1");
});
two.click(function(){
memory += "2";
show.val("2");
});
add.click(function(){
memory += "+";
if(show.val().length >= 1)
show.val("+");
else
show.val("");
});
equal.click(function(){
show.val(memory)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="show" type="text"/>
<input id="one" type="button" value="1"/>
<input id="two" type="button" value="2"/>
<input id="add" type="button" value="+"/>
<input id="equal" type="button" value="="/>

Categories