SereneAH
SereneAH

Reputation: 23

How do I return a value from a function in JavaScript to a textbox in HTML

This is my HTML code:

<head>

</head>

<body>

   LIMIT<input id='limit' name='' value='' class=''>

   <button id='go' class=''>GO</button>

   TOTAL<input id='total' name='' value='' class=''>

   <script src='js/limitfor.js'></script>


</body>

And this is my JavaScript:

document.getElementById('go').onclick = function () {

 var limit = document.getElementById('limit').value;

 limit = parseFloat(limit);

 total = 0;

 for (i=0; i<=limit ;i++) {

     total = total + i;        

 };

};

If I alert the total, I can see that the function works, but I need the total to be in the textbox rather than in a pop up alert.

Upvotes: 2

Views: 9673

Answers (4)

Ajay Rajput
Ajay Rajput

Reputation: 51

use document.getElementById(put id of the text area where you want to output your answer or result).value = answer(whatever is your answer or result you want to reflect in textbox or textarea)

enter image description here

Upvotes: 0

Karthik Haritha
Karthik Haritha

Reputation: 71

First select the particular element (i.e. total text field) in the form and set its value using assignment operator '='

document.getElementById("total").value=total;

Upvotes: 2

Sandeeproop
Sandeeproop

Reputation: 1776

Just assign the value in total text box after your for loop is completed

 var limit = document.getElementById('limit').value;

 limit = parseFloat(limit);

 total = 0;

 for (i=0; i<=limit ;i++) {

   total = total + i;        

};
document.getElementById("total").value = total; 

};

Upvotes: 0

Samuel Goodell
Samuel Goodell

Reputation: 630

You will need to set the value of the input element:

document.getElementById("total").value = total;

Upvotes: 3

Related Questions