I'm trying to get the values from the inputs in my form with JavaScript. But whenever I hit submit, I either get nothing, 0 or undefined. Mostly undefined. It doesn't seem to get any of the values.
Here's the code
<form id="ecoCalculator">
<div class="form-group">
<label for="k0">Start Kapital</label>
<input type="number" name="k0" class="form-control" id="k0">
</div>
<div class="form-group">
<label for="kn">Slut Kapital</label>
<input type="number" name="kn" class="form-control" id="kn">
</div>
<div class="form-group">
<label for="x">Rente</label>
<input type="number" name="x" class="form-control" id="x">
</div>
<div class="form-group">
<label for="n">Terminer</label>
<input type="number" name="n" class="form-control" id="n">
</div>
<div class="ecoButtons">
<input type="button" value="Udregn" class="btn btn-default" onclick="k0Eco()">
<input type="reset" value="Ryd" class="btn btn-default">
</div>
</form>
<div class="ecoResult">
<p id="ecoResult">Resultat</p>
</div>
</div>
<script type="text/javascript">
// Public Variables
var k0 = document.getElementById('k0').value();
var kn = document.getElementById('kn').value();
var x = document.getElementById('x').value();
var n = document.getElementById('n').value();
// Calculation of Initial Capital
function k0Eco() {
// Calculation
var k0Value = kn / (1 + x) ^ n;
// Show Result
document.getElementById("ecoResult").innerHTML = k0;
}
I've looked around at different questions but haven't found a solution to this yet.
I've tried to change the names of the inputs, having the function only display a single value, but still no result.
Thanks
value isn't a function, it's a property. Change
var k0 = document.getElementById('k0').value()
to
var k0 = document.getElementById('k0').value
Your script also runs on page load, so nothing is filled yet. You need to put the whole thing in a submit handler:
document.getElementById('ecoCalculator').addEventListener('submit', function(e) {
e.preventDefault();
// your code here
});
Now remove the inline js from the button and make it type submit:
<input type="submit" value="Udregn" class="btn btn-default" />
And remove the function in your js
var k0 = document.getElementById('k0').value;
var kn = document.getElementById('kn').value;
var x = document.getElementById('x').value;
var n = document.getElementById('n').value;
// Calculation
var k0Value = kn / (1 + x) ^ n;
// Show Result
document.getElementById("ecoResult").innerHTML = k0Value;
Here's a working fiddle
you need to parse the input value in int. for eg.
// Public Variables
var k0 = parseInt(document.getElementById('k0').value);
var kn = parseInt(document.getElementById('kn').value);
var x = parseIntdocument.getElementById('x').value);
var n = parseIntdocument.getElementById('n').value);
Use value instead of value(). It is a property not a function.
Put your variables inside your function. When page loads you variables
are getting the value of the inputs and there is nothing there.
function k0Eco() {
var k0 = document.getElementById('k0').value;
var kn = document.getElementById('kn').value;
var x = document.getElementById('x').value;
var n = document.getElementById('n').value;
var k0Value = kn / (1 + x) ^ n;
document.getElementById("ecoResult").innerHTML = k0Value;
}
Put you javascript code inside <head> tag or at least before the button. When you try to fire onclick() event, your function is not created yet.
Related
Hello guys so im new to js and i'm trying to make a simple programme that caculate delta but the problem is that i always the value of delta 0 but when i set a static value to delta like an int it show the value correct where is the probleme and thanks
var first = document.getElementById("Cofession1"),
second = document.getElementById("Cofession2"),
third = document.getElementById("Cofession3"),
displayMessage = document.getElementById("solution"),
a = first.value,
b = second.value,
c = third.value,
btnClick = document.getElementById("calculateButton");
btnClick.onclick = function () {
var delta = b*5;
displayMessage.innerHTML = "delta = " + delta;
}
and this is the html
<input type="text" name="" id="Cofession1" placeholder="The value of a">
<input type="text" name="" id="Cofession2" placeholder="The value of b">
<input type="text" name="" id="Cofession3" placeholder="The value of c">
<button id="calculateButton">Calculate</button>
<div id="solution"></div>
The values of a, b, and c do not update automatically: you will need to assign them within the onclick method so that they reflect the value at the time the button is clicked. Otherwise they will always be an empty string since they are only evaluated at runtime.
Also, I do not recommend assigning directly to onclick, but use the more modern addEventListener instead.
var first = document.getElementById("Cofession1");
var second = document.getElementById("Cofession2");
var third = document.getElementById("Cofession3");
var displayMessage = document.getElementById("solution");
btnClick = document.getElementById("calculateButton");
btnClick.addEventListener('click', function() {
// Assign values in the event handler
var a = first.value;
var b = second.value;
var c = third.value;
var delta = b * 5;
displayMessage.innerHTML = "delta = " + delta;
});
<input type="text" name="" id="Cofession1" placeholder="The value of a">
<input type="text" name="" id="Cofession2" placeholder="The value of b">
<input type="text" name="" id="Cofession3" placeholder="The value of c">
<button id="calculateButton">Calculate</button>
<div id="solution"></div>
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.
I am creating a simple equation solver that involves division. I have two text boxes, One for "Mass" and one for "Element". I want to create a variable "H" and set it equal to 1, that way when the user types in "2" in the mass box and "H" in the element box, the output will say "1".
Here is my HTML
<div id="GramsToMolesContainer"><div id="GramMolesText">
<font size=3>Grams To Moles</font></div>
<form>
Grams : <input type="text" id="GramsChoice" /><br>
Element : <input type="text" id="ElementChoice" /><br>
<input type="button" onClick="GramstoMoles()" Value="Convert" />
</form>
<p>Molar Mass : <br>
<span id = "resultMolarMass"></span>
</p>
</div>
Here is my Javascript:
function GramstoMoles()
{
var H = 1;
GramsState = document.getElementById("GramsChoice").value;
ElementState =
document.getElementById("ElementChoice").value;
document.getElementById("resultMolarMass").innerHTML
= GramsState / ElementState;
}
you will need to create a dictionary.
this is how your function should look. every time that you want to add an element - create a new key-value pair.
function GramstoMoles()
{
var elements = {h:1, he:2};
GramsState = document.getElementById("GramsChoice").value;
ElementState =
document.getElementById("ElementChoice").value;
document.getElementById("resultMolarMass").innerHTML
= parseInt(GramsState) / elements[ElementState];
}
Check this working snippet of your code!
If you wan to set H as an inital value of some box, do
var ElementState = document.getElementById("ElementChoice").value = H; before you call the function.
function GramstoMoles (){
var H = 1;
var GramsState = document.getElementById("GramsChoice").value;
var ElementState = document.getElementById("ElementChoice").value;
document.getElementById("resultMolarMass").innerHTML = GramsState / ElementState;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="GramsToMolesContainer"><div id="GramMolesText">
<font size=3>Grams To Moles</font></div>
<form>
Grams : <input type="text" id="GramsChoice" /><br>
Element : <input type="text" id="ElementChoice" /><br>
<input type="button" onClick="GramstoMoles()" Value="Convert" />
</form>
<p>Molar Mass : <br>
<span id = "resultMolarMass"></span>
</p>
</div>
When you get the var element and var grams ,
var elements = ['H','He','Li','Be',...];
var atomicmasses = [1,4,6,9,.....];
var molarmass = molarmasses[elements.indexOf(element)];
var mole = grams/molarmass;
The goal is to type in one text box a certain value (of pixels or centimeters) then to press a button, and the button to do some maths and show the result in a different text box.
What happens is, I'll get a result of 'NaN', implying that the string I inputted hadn't been converted properly. I've gone through hundreds of methods to fix this and it still doesn't work.
Code :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Conversion</title>
</head>
<body bgcolor=#FF0000>
<form id="conversions" name="conversions">
Pixel value :
<br>
<input type="text" name="pxvalue" id="pxvalue">
<br>
<input type="submit" name="convertcm" id="convertcm" value="Convert cm to px!">
<input type="submit" name="convertpx" id="convertpx" value="Convert px to cm!">
<br>Centimeter value :
<br>
<input type="text" name="cmvalue" id="cmvalue">
<br>
<br>Output :
<input type="text" name="output" id="output">
</form>
<!-- This is where all the JavaScript code goes -->
<script>
var form = document.getElementById("conversions");
var strcmvalue = form.elements["cmvalue"];
var strpxvalue = form.elements["pxvalue"];
var cmvalue = ToInteger(strcmvalue);
var pxvalue = ToInteger(strpxvalue);
var output = document.getElementById("output");
var ccmbutton = document.getElementById("convertcm").onclick = cm_to_pixel_conversion(cmvalue);
var cpxbutton = document.getElementById("convertpx").onclick = pixel_to_cm_conversion(pxvalue);
var cm_per_pixel = 0.026458333;
var px_per_cm = 37.795275591;
function pixel_to_cm_conversion(pvalue) {
cmconversion = pvalue / px_per_cm;
output.value = cmconversion.toString();
}
function cm_to_pixel_conversion(cvalue) {
pxconversion = cvalue / cm_per_pixel;
output.value = pxconversion.toString();
}
function ToInteger(x) {
x = Number(x);
return x < 0 ? Math.ceil(x) : Math.floor(x);
}
</script>
<!-- End of the JavaScript code-->
</body>
</html>
Because you are not passing a value to the method, you are passing an html element.
var strcmvalue = form.elements["cmvalue"]; //reference element
var strpxvalue = form.elements["pxvalue"];
var cmvalue = ToInteger(strcmvalue); //passing element, not the value
var pxvalue = ToInteger(strpxvalue);
You need strcmvalue.value or form.elements["cmvalue"].value
Next issue is the fact you read the values when the page loads, so you will only ever have the values from the time it loads.
So you should be reading the values and converting them to numbers inside of your methods, not when the page loads.
After that your click event is calling the function, not referencing it.
var ccmbutton = document.getElementById("convertcm").onclick = function () {
var num = parseInt(strcmvalue.value, 10);
cm_to_pixel_conversion(num);
return false;
};
I have a 4 form which has a button below it saying add more experience and add more education etc, when user clicks on the add more button the jquery creates a clone of the form and append it, the problem i'm getting is I'm not able to limit the number of clones here is code
$(".btn-duplicator").on("click", function(a) {
a.preventDefault();
var b = $(this).parent().siblings(".duplicateable-content"),
c = $("<div>").append(b.clone()).html();
$(c).insertBefore(b);
var d = b.prev(".duplicateable-content");
d.fadeIn(600).removeClass("duplicateable-content"), d.find(".btn-remove").on("click", function(a) {
a.preventDefault();
var b = $(this).parents(".item-block").parent("div");
b.fadeOut(600, function() {
b.remove()
})
})
});
i tried addding
var count = 1;
if(count < 5) {
count++;
}
but nothing seems to work how can i limit the cloning to only 5 forms
html structure for experience
<div class="col-xs-12 duplicateable-content">
<div class="form-group">
<input type="text" class="form-control" placeholder="Name">
</div>
<button class="btn btn-primary btn-duplicator">Add experience</button>
</div>
structure for education & more
<div class="col-xs-12 duplicateable-content">
<div class="form-group">
<input type="text" class="form-control" placeholder="name">
</div>
<button class="btn btn-primary btn-duplicator">Add Education</button>
</div>
Your var count=1 depends on where you declare it.
If you declare var count inside click handler it will always be set to one each click. If you declare it outside click handler it will increment.
var count = 1; // will work
$(".btn-duplicator").on("click", function(a) {
var count = 1; // won't work - is same value every click
Can also count elements
if( $(".duplicateable-content").length >=5 ){
alert('Only allowed 5');
return;// don't proceed to clone code
}
Add the following after:
$(".btn-duplicator").on("click", function(a) {
var noClones = $(this).data('clones') || 0;
$(this).data('clones', ++noClones);
if (noClones > 5) return;
// ...
// ...