1

function addData (n1, n2) {
    alert(fn+ln);
}
 <body>
   <input Type="text" name="n1">
   <input Type="text" name="n2">
   <button onClick="addData(n1.value,n2.value)">click</button> 
</body>

its give me the following error:

ReferenceError: n1 is not defined.

3 Answers 3

1

You cannot get the value of the input by using n1.value You need to obtain the DOM element using document.getElementById and use its value to obtain the string value and parse it as Integer before you add them.

See this:

function addData (n1, n2) {
    n1Val = parseInt(n1.value);
    n2Val = parseInt(n2.value);
    alert(n1Val+n2Val);
}
<body>
    <input Type="text" id="n1">
    <input Type="text" id="n2">
    <button onClick="addData(document.getElementById('n1'), document.getElementById('n2'))">click</button> 
</body>

If you want to merely concatenate the data and not add it, just remove the parseInt call and add the strings like in the following example:

function addData (n1, n2) {
	n1Val = n1.value;
    n2Val = n2.value;
    alert(n1Val+n2Val);
}
<body>
    <input Type="text" id="n1">
    <input Type="text" id="n2">
    <button onClick="addData(document.getElementById('n1'), document.getElementById('n2'))">click</button>  
</body>

Hope it helps!!

Sign up to request clarification or add additional context in comments.

1 Comment

tnks varun, but my input field name not fix thats why i need to pass value in html page.
0

Do like this way:

function addData (e) {
var rec = 0;
var t = document.getElementsByTagName('input');
for(var i=0;i<t.length;i++){
rec=rec+parseInt(t[i].value);
}
console.log(rec);
}
<script>
   
</script>

<body>
    <input Type="text" name="n1">
    <input Type="text" name="n2">
    <button onClick="addData(this)">click</button> 
</body>

Comments

0

<html>
    <head>
        <title>Input tutorial</title>
        <script language="javascript">
            function addNumbers()
            {
                var val1 = parseInt(document.getElementById("value1").value);
                var val2 = parseInt(document.getElementById("value2").value);
                var ansD = document.getElementById("answer");
                var final = val1 + val2;
                alert(final);
            }
        </script>
    </head>
     
    <body>
        value1 = <input type="text" id="value1" name="value1" value="1" /> value2 = <input type="text" id="value2" name="value2" value="2" />
        <input type="button" name="Sumbit" value="Click here" onclick="javascript:addNumbers()" /> 
    </body> 

</html>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.