1

I want to store the value given in the text box in a variable. I am beginner to javascript. Please help me out. Here s my code.

<!DOCTYPE html>
<html>
<body>

Days of Journey: <input type="text" id="doj" name="daysofjourney">
<input type="button" value="submit" onclick="dayscounter()">

<script language="javascript" type="text/javascript">
var travel = document.getElementById("doj").value;

function dayscounter() {
    var days;
    for(days = 1; days <= travel; days++) {
        document.write(days);
    }
}
</script>

</body>
</html>  
akinuri
  • 10,690
  • 10
  • 65
  • 102
user2969182
  • 23
  • 1
  • 1
  • 4
  • Hi, have a look at this question: http://stackoverflow.com/questions/11563638/javascript-get-input-text-value – homtg Nov 10 '13 at 13:00
  • Checked. But cant get my answer. I have used a loop to find out whether it s working or not. My output was none.If i replace the value of travel by any number i am getting output. Thats wat my problem is, the variable value is not stored. :( – user2969182 Nov 10 '13 at 13:05

3 Answers3

2

You nearly had it already...

function dayscounter() {
    var travel = document.getElementById("doj").value;
    var days;
    for(days=1;days<=travel;days++)
    {
        document.write(days);
    }
}

The problem was, that your first assignment of the variable travel is made as soon as the HTML code is loaded. The user can't have made an input yet at that time, thus the variable stays empty. If you include document.getElementById("doj").value inside the function, you will get the value at that specific time you launch the function.

Zim84
  • 3,404
  • 2
  • 35
  • 40
1

Just parse value to int

var travel = +(document.getElementById("doj").value;);
Vicky Gonsalves
  • 11,593
  • 2
  • 37
  • 58
0

You can use 'value' attribute of an text input to set it's value like:

<input type="text" id="textid" value="value content" />

and you can do your function like this:

<script language="javascript" type="text/javascript">
function dayscounter()
{   
    var travel = document.getElementById("doj").value;
    var days;
    var result = "";

    for (days = 1; days <= parseInt(travel); ++days)
    {
        document.getElementById("result").value += " " + days;
    }
}
</script>


Days of Journey:
<input type="text" id="doj" name="daysofjourney" />
<input type="button" value="submit" onclick="dayscounter()" />

<p>
    <input type="text" id="result" />
</p>
Wenchao You
  • 43
  • 1
  • 3