0

I'm trying to learn Javascript and I feel like I have a decent grasp on the fundamentals but I am having problems making it do things that i want .. for example.. I am trying to create a simple form in html that calculates the sum of 2 numbers.. here is my html and javascript:

<head>
    <script type="text/javascript">
        function adder(a,b) {
            var a = document.getElementById('firstNum').value;
            var b = document.getElementById('secondNum').value;
            var numbers = new Array(a,b);
            var sum = 0;

            for (i=0; i < numbers.length; i++) {
                sum += parseInt(numbers[i]);
            }

            //this part i need help with
            document.getElementById('answer').write("First Number: " + a + " plus Second Number: " + b + " is " + sum).value; //this part i need help with
    </script>
</head>
<body>
    <form id="additionForm">
        A + B = C : <input type="text" id="firstNum" placeholder="A"> 
        + <input type="text" id="secondNum" placeholder="B">
        <input type="button" id="addBtn" value="Add" onClick="adder();">
        = <input type="text" id="answer" placeholder="C">
    </form>
</body>

My problem is that i don't know how to get the javascript to overwrite the value attribute for my form input id=answer .. or if i'm supposed to be using Jquery instead .. thanks in advance.

1
  • "or if i'm supposed to be using Jquery instead" Please don't forget this: there is nothing that jQuery can do and plain JavaScript cannot. Commented Oct 12, 2014 at 21:26

2 Answers 2

3
function adder() {
  var a = parseInt( document.getElementById('firstNum').value, 10);
   var b = parseInt( document.getElementById('secondNum').value, 10);
   var sum = a + b;

  //this part i need help with
  document.getElementById('answer').value = "First Number: " + a + " plus Second Number: " + b + " is " + sum).value; //this part i need help with
}
Sign up to request clarification or add additional context in comments.

1 Comment

ahh parseInt .. i've never seen that before but i learned a bit of python before and i remember that basically any input from the user is a string .. so you must change the input into a number before you can just simply say var sum = a + b; otherwise you are just joining strings.. thank you!
2

If you want to modify an input field in javascript, you can simply set the value attribute:

document.getElementById('answer').value = "First Number: " + a + " plus Second Number: " + b + " is " + sum;

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.