Passing HTML input value as a JavaScript Function Parameter - javascript

I am new to JavaScript, and I'm trying to figure out how to pass user-inputted values as a parameter to a JavaScript function. Here is my code:
<body>
<h1>Adding 'a' and 'b'</h1>
<form>
a: <input type="number" name="a" id="a"><br>
b: <input type="number" name="b" id="a"><br>
<button onclick="add(a,b)">Add</button>
</form>
<script>
function add(a,b) {
var sum = a + b;
alert(sum);
}
</script>
</body>

One way is by using document.getElementByID, as below -
<body>
<h1>Adding 'a' and 'b'</h1>
a: <input type="number" name="a" id="a"><br> b: <input type="number" name="b" id="b"><br>
<button onclick="add(document.getElementById('a').value,document.getElementById('b').value)">Add</button>
<script>
function add(a, b) {
var sum = parseInt(a, 10) + parseInt(b, 10);
alert(sum);
}
</script>
</body>

Firstly an elements ID should always be unique. If your element IDs aren't unique then you would always get conflicting results. Imagine in your case using two different elements with the same ID.
<form>
a: <input type="number" name="a" id="a"><br>
b: <input type="number" name="b" id="b"><br>
<button onclick="add()">Add</button>
</form>
<script>
function add() {
var a = document.getElementById('a').value;
var b = document.getElementById('b').value;
var sum = parseInt(a) + parseInt(b);
alert(sum);
}
</script>

1 IDs are meant to be unique
2 You dont need to pass any argument as you can call them in your javascript
<form>
a: <input type="number" name="a" id="a"><br>
b: <input type="number" name="b" id="b"><br>
<button onclick="add()">Add</button>
</form>
<script>
function add() {
var a = document.getElementById('a').value;
var b = document.getElementById('b').value;
var sum = a + b;
alert(sum);
}
</script>

<form action="" onsubmit="additon()" name="form1" id="form1">
a: <input type="number" name="a" id="a"><br>
b: <input type="number" name="b" id="b"><br>
<input type="submit" value="Submit" name="submit">
</form>
<script>
function additon()
{
var a = document.getElementById('a').value;
var b = document.getElementById('b').value;
var sum = parseInt(a) + parseInt(b);
return sum;
}
</script>

You can get the values with use of ID. But ID should be Unique.
<body>
<h1>Adding 'a' and 'b'</h1>
<form>
a: <input type="number" name="a" id="a"><br>
b: <input type="number" name="b" id="b"><br>
<button onclick="add()">Add</button>
</form>
<script>
function add() {
a = $('#a').val();
b = $('#b').val();
var sum = a + b;
alert(sum);
}
</script>
</body>

do you use jquery?
if then:
$('#xx').val();
or use original javascript(DOM)
document.getElementById('xx').value
or
xxxform.xx.value;
if you want to learn more, w3chool can help you a lot.

Use this it will work,
<body>
<h1>Adding 'a' and 'b'</h1>
<form>
a: <input type="number" name="a" id="a"><br>
b: <input type="number" name="b" id="a"><br>
<button onclick="add()">Add</button>
</form>
<script>
function add() {
var m = document.getElementById("a").value;
var n = document.getElementById("b").value;
var sum = m + n;
alert(sum);
}
</script>
</body>

I like how most answers here don't know that javascript accepts every input as string unless we use parseInt.
Yes, you can pass parameters in that way.
Just a little modification
Var sum = parseFloat(a)+parseFloat (b);
Try it (⁠。⁠•̀⁠ᴗ⁠-⁠)⁠✧

Related

how to increment and decrement the text box value using javascript?

i am trying increment and decrement a number if user is giving in text box is 15 it should be incremented when click a button and also decrement when button clicking...
this is my javascript code
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function incNumber() {
for(i=1;i>0;i++){
document.getElementById("display").value=i;
}
}
function decNumber() {
for(i=1;i>0;i--){
document.getElementById("display").value=i;
}
}
</script>
</head>
<body>
<form>
<input type="text" value="0"/>
<input type="button" value="Increase" id="inc" onclick="incNumber()"/>
<input type="button" value="Decrease" id="dec" onclick="decNumber()"/>
<label id="display"></label>
</form>
</body>
</html>
Use parseInt() function to convert the value from string to integer.
function incNumber(){
var c = parseInt(document.getElementsByTagName("input")[0].value);
c++;
document.getElementsByTagName("input")[0].value = c;
document.getElementById("display").innerHTML = c;
}
The logic stands for decNumber()
function decNumber(){
var c = parseInt(document.getElementsByTagName("input")[0].value);
c--;
document.getElementsByTagName("input")[0].value = c;
document.getElementById("display").innerHTML = c;
}
Few suggestions
1.Never mix up your markup with javascript. Consider attaching events click/change at javascript end
DOM search is costly.use it cautiously
3.Use parseInt(variablename,10) ->to convert it into integer
check the following snippet
window.onload=function(){
var incButton=document.getElementById("inc");
incButton.addEventListener("click",incNumber);
var decButton=document.getElementById("dec");
decButton.addEventListener("click",decNumber);
}
function incNumber() {
var displayValue= document.getElementById("display");
var text=document.getElementById("input");
var value=parseInt(text.value,10);
if(value==15){
displayValue.innerHTML=value+1;
}
}
function decNumber() {
var displayValue= document.getElementById("display");
var text=document.getElementById("input");
var value=parseInt(text.value,10);
displayValue.innerHTML=value-1;
}
<form>
<input type="text" value="0" id="input"/>
<input type="button" value="Increase" id="inc" />
<input type="button" value="Decrease" id="dec" />
<label id="display"></label>
</form>
Hope this helps
If you want to increment the label value by the input value try this
function incNumber(){
var num=0;
if(isNaN(document.getElementById('diplay').innerHTML)){
num=$("#inputVal").val();
}
else{
num=parseInt(document.getElementById('diplay').innerHTML)+$("#inputVal").val();
}
document.getElementById('diplay').innerHTML=num;
}
function decNumber(){
var num=0;
if(isNaN(document.getElementById('diplay').innerHTML)){
num=$("#inputVal").val();
}
else{
num=parseInt(document.getElementById('diplay').innerHTML)-$("#inputVal").val();
}
document.getElementById('diplay').innerHTML=num;
}
In HTML
<form>
<input type="number" id="inputVal" value="0"/>
<input type="button" value="Increase" id="inc" onclick="incNumber()"/>
<input type="button" value="Decrease" id="dec" onclick="decNumber()"/>
<label id="display"></label>
or you can define input type as number
<input type="number" id="numbrfield"/>
you will automatically get buttons to increment or decrement when you hover on the field.

Trying to make a form to calculate compounded interest

I've found different types of snippets on here calculating interest and so forth but unable to find the help I need.
I'm making a simple form and using Javascript to find the compounded interest and output it in HTML.
I've used the getDocumentById with and without the innerHTML as well as placing it in parseInt(). Long story short, I get 'NaN' as output.
Take a look at what I finished up with and maybe someone can point me as to what I might be missing. Thanks
<form onsubmit="return false">
<input id="a" name="a" type="number" step="any" placeholder="Present Value"> * (
<input id="b" name="b" type="number" step="any" placeholder="Number of years"> +
<input id="c" name="c" type="number" step="any" placeholder="Interest Rate">)^
<input id="d" name="d" type="number" step="any" placeholder="N number of Years">=
<button onclick="futureNyears()">Answer</button>
<p id="futureNanswer"></p>
</form>
<script type="text/javascript">
function futureNyears() {
var a = parseInt(document.getElementById('a'));
var b = parseInt(document.getElementById('b'));
var c = parseFloat(document.getElementById('c'));
var d = parseInt(document.getElementById('d'));
var E = eval(b+c);
var r = Math.pow(E, d);
var f = eval(E * r);
var g = f.toString();
document.getElementById("futureNanswer").innerHTML = g;
}
</script>
After getting element by ID, you need to access the value attribute, parseInt received DOM object which equated to NaN all time.
function futureNyears() {
var a = parseInt(document.getElementById('a').value);
var b = parseInt(document.getElementById('b').value);
var c = parseFloat(document.getElementById('c').value);
var d = parseInt(document.getElementById('d').value);
var E = (b+c);
var r = Math.pow(E, d);
var f = (E * r);
var g = f.toString();
document.getElementById("futureNanswer").innerHTML = g;
}
<form onsubmit="return false">
<input id="a" name="a" type="number" step="any" placeholder="Present Value"> * (
<input id="b" name="b" type="number" step="any" placeholder="Number of years"> +
<input id="c" name="c" type="number" step="any" placeholder="Interest Rate">)^
<input id="d" name="d" type="number" step="any" placeholder="N number of Years">=
<button onclick="futureNyears()">Answer</button>
<p id="futureNanswer"></p>
</form>
document.getElementById('a') return the dom element so you have to get the value out of it like below
var a = parseInt(document.getElementById('a').value);
In your case you forgot to write document.getElementById('a').value() because its a form element and you cannot extract its value without value() attribute.
Parseint() always return the first number detected in your string .
You need to use the .value property to return the value of the particular element.
var a = parseInt(document.getElementById('a').value);
The value property sets or returns the value of the option (the value to be sent to the server when the form is submitted)
HTML
<!DOCTYPE html>
<html>
<head>
<title>CI</title>
</head>
<body>
<form onsubmit="return false">
<input id="a" name="a" type="number" step="any" placeholder="Present Value"> * (
<input id="b" name="b" type="number" step="any" placeholder="Number of years"> +
<input id="c" name="c" type="number" step="any" placeholder="Interest Rate">)^
<input id="d" name="d" type="number" step="any" placeholder="N number of Years">=
<button onclick="futureNyears()">Answer</button>
<p id="futureNanswer"></p>
</form>
</body>
</html>
JavaScript
<script type="text/javascript">
function futureNyears() {
var a = parseInt(document.getElementById('a').value);
var b = parseInt(document.getElementById('b').value);
var c = parseFloat(document.getElementById('c').value);
var d = parseInt(document.getElementById('d').value);
var E = eval(b+c);
var r = Math.pow(E, d);
var f = eval(E * r);
var g = f.toString();
document.getElementById("futureNanswer").innerHTML = g;
}
</script>
In order to get a value from input text box use
var a = parseInt(document.getElementById('a').value);
instead of
var a = parseInt(document.getElementById('a'));
<form onsubmit="return false">
<input id="a" name="a" type="number" step="any" placeholder="Present Value"> * (
<input id="b" name="b" type="number" step="any" placeholder="Number of years"> +
<input id="c" name="c" type="number" step="any" placeholder="Interest Rate">)^
<input id="d" name="d" type="number" step="any" placeholder="N number of Years">=
<button onclick="futureNyears()">Answer</button>
<p id="futureNanswer"></p>
</form>
<script type="text/javascript">
function futureNyears() {
var a = parseInt(document.getElementById('a').value);
var b = parseInt(document.getElementById('b').value);
var c = parseFloat(document.getElementById('c').value);
var d = parseInt(document.getElementById('d').value);
var E = eval(b+c);
var r = Math.pow(E, d);
var f = eval(E * r);
var g = f.toString();
document.getElementById("futureNanswer").innerHTML = g;
}
</script>

Button onclick, count the total price (Javascript)

This should be pretty simple, but I can't get it right. When I click the button with onclick event to a function, the total price won't show up on the input. What's wrong with my code?
<html>
<body>
<h1>KASIR</h1>
<form>
-------<b>Nama Barang</b>----------------------------<b>Harga</b>--------
<br>
<input type=text> Rp.
<input id="a" type=number>
<br>
<input type=text> Rp.
<input id="b" type=number>
<br>
<input type=text> Rp.
<input id="c" type=number>
<br>
<input type=text> Rp.
<input id="d" type=number>
<br>
<br>
<button onclick="fungsi()">Hitung!</button> <b>Total</b> Rp.
<input id="total" type=number>
</form>
<script>
var a = document.getElementById("a").value;
var b = document.getElementById("b").value;
var c = document.getElementById("c").value;
var d = document.getElementById("d").value;
var total = a + b + c + d;
function fungsi() {
document.getElementById("total").value = total;
}
</script>
</body>
</html>
this works
function fungsi() {
var a = document.getElementById("a").value;
var b = document.getElementById("b").value;
var c = document.getElementById("c").value;
var d = document.getElementById("d").value;
var total = parseFloat(a) + parseFloat(b) + parseFloat(c) + parseFloat(d);
document.getElementById("total").value = total;
}
<h1>KASIR</h1>
<form>
-------<b>Nama Barang</b>----------------------------<b>Harga</b>--------
<br>
<input type=text>Rp.
<input id="a" type=number>
<br>
<input type=text>Rp.
<input id="b" type=number>
<br>
<input type=text>Rp.
<input id="c" type=number>
<br>
<input type=text>Rp.
<input id="d" type=number>
<br>
<br>
<button onclick="fungsi()">Hitung!</button> <b>Total</b> Rp.
<input id="total" type=number>
</form>
first of all your page are refreshing due to form and button that would be require to prevent.
below i have provided code.
<form>
<br>
<input type=text> Rp.
<input id="a" type=number>
<br>
<input type=text> Rp.
<input id="b" type=number>
<br>
<input type=text> Rp.
<input id="c" type=number>
<br>
<input type=text> Rp.
<input id="d" type=number>
<br>
<br>
<button id="buttonClick" >Hitung!</button> <b>Total</b> Rp.
<input id="total" type="button"/>
</form>
<script>
$("#buttonClick").click(function (event) {
event.preventDefault();
var a = document.getElementById("a").value;
var b = document.getElementById("b").value;
var c = document.getElementById("c").value;
var d = document.getElementById("d").value;
var total = a + b + c + d;
document.getElementById("total").value = total;
alert('jkhejhS');
});
</script>
You need to capture the values inside the function, not when the script is first run.
Also, adding type="button" to the button stops it submitting the form.
ie:
function fungsi(){
var a = parseFloat(document.getElementById("a").value);
var b = parseFloat(document.getElementById("b").value);
var c = parseFloat(document.getElementById("c").value);
var d = parseFloat(document.getElementById("d").value);
a = a ? a : 0;
b = b ? b : 0;
c = c ? c : 0;
d = d ? d : 0;
var total = a + b + c + d;
document.getElementById("total").value = total;
}
function fungsi() {
var a = parseFloat(document.getElementById("a").value);
var b = parseFloat(document.getElementById("b").value);
var c = parseFloat(document.getElementById("c").value);
var d = parseFloat(document.getElementById("d").value);
a = a ? a : 0;
b = b ? b : 0;
c = c ? c : 0;
d = d ? d : 0;
var total = a + b + c + d;
document.getElementById("total").value = total;
}
<form>
-------<b>Nama Barang</b>----------------------------<b>Harga</b>------
<br>
<input type=text>Rp.
<input id="a" type=number>
<br>
<input type=text>Rp.
<input id="b" type=number>
<br>
<input type=text>Rp.
<input id="c" type=number>
<br>
<input type=text>Rp.
<input id="d" type=number>
<br>
<br>
<button onclick="fungsi()" type="button">Hitung!</button> <b>Total</b>Rp.
<input id="total" type=number>
</form>
There are a couple of issues with your code.
The JavaScript is executed while the page loads. That means you are getting the input values before the user had a chance to enter them.
total, a, b, etc. won't magically update their values when the user enters the values in the inputs. You have to retrieve the values when the button was clicked, i.e. inside the event handler. However, you can store a reference to the DOM elements themselves so that you do not have to look for them every time the button is pressed.
For easy of use later on, I suggest to put them into an array:
// Array of input elements
var inputs = [
document.getElementById("a"),
document.getElementById("b").
// ...
];
var total = document.getElementById("total");
function fungsi() {
// here you get their values e.g.
console.log(inputs[0].value);
// but we will see a better way to compute the total
}
Instead of getting every input individually by ID, you can also use document.querySelectorAll, to select all of them "at once":
var inputs = [].slice.call(document.querySelectorAll('input[type=number]'));
The [].slice.call part is necessary to convert the NodeList returned by querySelectorAll into an actual array.
a + b + c + d performs string concatenation instead of addition, because .value returns a string. I.e. if the inputs are 1, 2, 3 and 4, the value of total would be the string "1234" instead of the number 10.
You have to convert the values to numbers first. There various ways to do this. One of them is to pass the string value to the Number function.
To sum the values we can use .reduce if you put the DOM elements inside the array.
Example:
function fungsi() {
var sum = inputs.reduce(function(sum, input) {
return sum + Number(input.value);
}, 0);
total.value = sum;
}
<button> elements are submit buttons by default, i.e. clicking the button will submit the form. This will cause the browser send a request to the target of the form and load that side. Since you did not provide a target, the browser will basically reload the page, so you won't see the changes made by JavaScript.
You can disable this behavior by declaring the button as "dummy" button, using type="button":
<button type="button" onclick="fungsi()">Hitung!</button>
DEMO
var inputs = [].slice.call(document.querySelectorAll('input[type=number]'));
var total = document.getElementById("total");
function fungsi() {
var sum = inputs.reduce(function(sum, input) {
return sum + Number(input.value);
}, 0);
total.value = sum;
}
<h1>KASIR</h1>
<form>
-------<b>Nama Barang</b>----------------------------<b>Harga</b>--------
<br>
<input type=text>Rp.
<input id="a" type=number>
<br>
<input type=text>Rp.
<input id="b" type=number>
<br>
<input type=text>Rp.
<input id="c" type=number>
<br>
<input type=text>Rp.
<input id="d" type=number>
<br>
<br>
<button type="button" onclick="fungsi()">Hitung!</button> <b>Total</b> Rp.
<input id="total" type=number>
</form>
Write Your function like this...
function fungsi() {
var a = document.getElementById("a").value;
var b = document.getElementById("b").value;
var c = document.getElementById("c").value;
var d = document.getElementById("d").value;
var total = a + b + c + d;
document.getElementById("total").value = total;
}
Thats right, first of all remove form tag as it will refresh the page second convert your variables from string to number like this..
function fungsi(){
var a = Number(document.getElementById("a").value);
var b = Number(document.getElementById("b").value);
var c = Number(document.getElementById("c").value);
var d = Number(document.getElementById("d").value);
var total = a + b + c + d;
document.getElementById("total").value = total;
}

Putting all the output in a specific textbox in a while loop in JavaScript

So all I want here to happen is that how can I put all the given output in the answer textbox.
UPDATE
<html>
<body>
<script type="text/javascript">
function myFunction() {
var x = parseInt(document.f1.n1.value);
var y = parseInt(document.f1.n2.value);
if(x>=y) {
document.write("Invalid");
}
while (x<y)
{
document.write(x)
x=x+1;
}
}
</script>
<form name=f1 onsubmit="return false">
First no. <input type="text" name="n1">
Second no. <input type="text" name="n2">
Answer: <input type="text" name="ans" disabled>
<input type="submit" onClick="myFunction()">
</form>
</body>
</html>
Thank you in advance
You can do something like this:
Give answer input an id:
<input id="answerTextBox" type="text" name="ans" disabled>
After while loop populate answer textbox:
while (x>y)
{
document.getElementById("answerTextBox").value += ("" + x);
x=x+1;
}
This will put x and y in your answer textbox.
UPDATE******
<html>
<body>
<script type="text/javascript">
function myFunction() {
document.getElementById("answerTextBox").value = "";
var x = parseInt(document.getElementById("n1").value);
var y = parseInt(document.getElementById("n2").value);
if(x >= y)
{
document.getElementById("answerTextBox").value = "Invalid Input";
}
while (x < y)
{
document.getElementById("answerTextBox").value += ("" + x);
x=x+1;
}
}
</script>
First no. <input type="text" name="n1" id="n1">
Second no. <input type="text" name="n2" id="n2">
Answer: <input id="answerTextBox" type="text" name="ans" readonly>
<input type="button" onClick="myFunction()">
</form>
</body>
</html>
UPDATE for exponential************************
<html>
<body>
<script type="text/javascript">
function myFunction() {
document.getElementById("answerTextBox").value = "";
var x = parseInt(document.getElementById("n1").value);
var y = x;
var answer = 1;
for(var i = 0; i < y; i++)
{
answer = answer * x;
}
document.getElementById("answerTextBox").value = answer;
}
</script>
Enter Number: <input type="text" name="n1" id="n1">
Answer: <input id="answerTextBox" type="text" name="ans" readonly>
<input type="button" value="Submit" onClick="myFunction()">
</form>
</body>
</html>
UPDATE Add Exponents*****************
<html>
<body>
<script type="text/javascript">
function myFunction() {
document.getElementById("answerTextBox").value = "";
var x = parseInt(document.getElementById("n1").value);
var y = parseInt(document.getElementById("n2").value);
var answer = 0;
for(var i = 0; i <= y; i++)
{
answer = answer + Math.pow(x, i);
}
document.getElementById("answerTextBox").value = answer;
}
</script>
Enter Base Number: <input type="text" name="n1" id="n1">
Enter Highest Exponent: <input type="text" name="n2" id="n2">
Answer: <input id="answerTextBox" type="text" name="ans" readonly>
<input type="button" value="Submit" onClick="myFunction()">
</form>
</body>
</html>
<html>
<body>
The number inserted in the textbox is the number of exponent it will generate. The sample is 3. 3X3X3 is 27. <br>
<script type="text/javascript">
function myFunction() {
var x = document.f1.n1.value;
while(x<27)
{
x=x*3;
}
document.write(x)
}
</script>
<form name="f1" onsubmit="return false">
First no. <input type="text"name="n1" value=3 disabled>
<input type="submit" onClick="myFunction()">
</form>
</body>
</html>
Update: The Exponent in any number.

Need basic loop for js to sum two fields, since they're multiple groups

I need a basic loop to sum two fields. I just get it to work for one group, but the others remain the same. I know I need some kind of array to solve this, but I can't work it out. (Notice, they are 50 groups in the original project, but I just added 2) Here is the code:
HTML
<label>Value 1:</label><input type="text" name="value1[]" id="txtval1"><br>
<label>Value 2:</label><input type="text" name="value2[]" id="txtval2"><br>
<label>Total:</label><input type="text" name="total[]" id="txttotal"><br><br>
<label>Value 1:</label><input type="text" name="value1[]" id="txtval1"><br>
<label>Value 2:</label><input type="text" name="value2[]" id="txtval2"><br>
<label>Total:</label><input type="text" name="total[]" id="txttotal">
<br><br>
<button type="button" onclick="myFunction(); return false;">Get Total</button>
Javascript
<script type="text/javascript">
function myFunction()
{
var val1 = document.getElementById('txtval1').value;
var val2 = document.getElementById('txtval2').value;
var total = document.getElementById('txttotal');
var sum = parseInt(val1) + parseInt(val2);
if (val1.value!='' && val2.value!=''){
total.value='';
total.value = total.value + sum;
}
}
</script>
I don't know why this doen't work on my fiddle, but does in my local machine. Here is the Fiddle
I think that giving the same ID to two elements It is mistake.
You have to give a different ID for each element and pass them on for.
Look at this fiddle:
http://jsfiddle.net/83m6e/
EDIT: I changed the fiddle for option2:
http://jsfiddle.net/83m6e/3/
You also can put each segment into a div and then do not change the names.
You can not add up to arrays in order to add up their elements. You must do it one by one. Try this code:
<html>
<head>
<script type="text/javascript">
function myFunction()
{
var count = 3;
var val1, val2, sum;
for (var i = 0; i < count; i++)
{
val1 = document.getElementById('txtval1_' + i).value;
val2 = document.getElementById('txtval2_' + i).value;
sum = parseInt(val1) + parseInt(val2);
document.getElementById('txttotal_' + i).value = sum;
}
}
</script>
</head>
<body>
<label>Value 1:</label><input type="text" id="txtval1_0"><br>
<label>Value 2:</label><input type="text" id="txtval2_0"><br>
<label>Total:</label><input type="text" id="txttotal_0"><br><br>
<label>Value 1:</label><input type="text" id="txtval1_1"><br>
<label>Value 2:</label><input type="text" id="txtval2_1"><br>
<label>Total:</label><input type="text" id="txttotal_1"><br><br>
<label>Value 1:</label><input type="text" id="txtval1_2"><br>
<label>Value 2:</label><input type="text" id="txtval2_2"><br>
<label>Total:</label><input type="text" id="txttotal_2"><br><br>
<button type="button" onclick="myFunction(); return false;">Get Total</button>
</body>
</html>

Categories