Member Avatar for david.roun.7_1

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>

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>
Member Avatar for david.roun.7_1

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 :)

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

I don't know what you mean be this.

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.