0

Why is it that, the only way this will work is if I pass the entire:

add(document.getElementById('num1').value)

to the function, as opposed to simply adding: add(num1)

<script>
function add(num1){
total=num1*1+3;
alert(total);
}
</script>
</head>
<body>
<input type="text" id="num1" size="4">
<input type="button" onClick="add(document.getElementById('num1').value)";
</body>
</html>
3
Contributors
4
Replies
16
Views
3 Years
Discussion Span
Last Post by Airshow
0

as opposed to simply adding: add(num1)

Do you mean this... <input type="button" onClick="add(num1)" />

That doesnt work because "num1" doesnt have value. Just because you are using "num1" as the ID of the input element doesnt mean you can use it that way.

Maybe you are confused because you are using "num1" as the ID of the input element, but you are also using it in the function as the name of the parameter that the function accepts? It doesnt have to be the same. You could have a function called add that accepts a parameter called abc, or number as an example, such as... function add(number) {

Here is another way of writing your function so you dont have to pass it that way...

<!DOCTYPE html>
<html>
<head>

<script>

 function add(){
   var x = document.getElementById('num1').value;
   var total = x * 1 + 3;
   alert(total);
 }

</script>

</head>
<body>

 <input type="text" id="num1" size="4">
 <input type="button" onclick="add()" value="Add" />

</body>
</html>

Edited by JorgeM

0

Thanks for the information. I'm trying to learn how to pass arguments based on user input. Can you tell me how to word the input so the function recognizes it?

And yeah, I'm generally confused :)

0

Can you tell me how to word the input so the function recognizes it

I don't know what you mean be this.

0

David, when you call a function you pass parameters. In the function, references to the parameters are called arguments or sometimes formal variables.

Get your mind round arguments and parameters and everything will become clear.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.