Jim Jamesy
Jim Jamesy

Reputation: 7

Looping a javascript input to a html form

I'm using javascript to enter text into my webpage in a form. I'm using numbers for my test, starting at 1 and incrementing by one to 1000.

num=1

while (num<1001){
  document.getElementById('numberIn').value=num
  document.forms[0].submit()
  num+1
}

While it puts in the first number (1) and submits, it then freezes and fails to do anything further. The form just directs back to the current page when it is submitted. How can I get it to loop properly, inputting 1, submitting, directing back to the same page (blank), inputting 2, submitting again, etc, etc? Thanks

Upvotes: 0

Views: 131

Answers (6)

shan
shan

Reputation: 1

When the page is reloaded, the variable num is re-initialized to 1. Thus this makes an infinite loop of page refresh. Use some persistent storage mechanism like localStorage to retain the variable value after page refresh to avoid this problem.

if(localStorage.getItem("num") == null || localStorage.getItem("num") == 'null'){
    localStorage.setItem("num", 1);
    num=Number(localStorage.getItem("num"));
    while (num<1001){
      //debugger;
      document.getElementById('numberIn').value=num;
      console.log(num);
      document.forms[0].submit();
      num++;
    }
  }

You can uncomment the debugger in while loop to see the updating values, step by step. Call this reset function if you need to reset the persistent variable

reset = function(){ localStorage.getItem("num", null); }

Upvotes: 0

Beginner
Beginner

Reputation: 4153

try this just use sessionStorage to increment your value even your page refresh. edit your sessionStorage to num + 1 when your num is still less than limit

if ( localStorage.getItem('completed') == "true" ) {
  console.log('Completed');

  // do something here
} else {
  var num = (localStorage.getItem('num') == null) ? 1 : localStorage.getItem('num');
  num = parseInt(num);

  if (num < 5) {
    localStorage.removeItem('num');
    localStorage.setItem('num', num+1);

    document.getElementById('numberIn').value=num
    document.forms[0].submit();
  } else {
    localStorage.setItem('completed',true);
  }
}

Upvotes: 0

enhzflep
enhzflep

Reputation: 13109

Any reason not to use AJAX I wonder?

With it, you can request or submit info without leaving the current page. In this case, it sounds ideal. We can programmatically fill input(s) on the form, submit it, change elements and submit it again - as many times as we please.

Here's a quick'n'dirty sample implementation.

It prints to the console 10 times.

0
1
2
3
4
5
6
7
8
9

1. FormAction.html

<!DOCTYPE html>
<html>
<head>
<script>
"use strict";
function byId(id){return document.getElementById(id);}

function myAjaxPostForm(url, formElem, successCallback, errorCallback)
{
    var ajax = new XMLHttpRequest();
    ajax.onreadystatechange = function()
    {
        if (this.readyState==4 && this.status==200)
            successCallback(this);
    }
    ajax.onerror = function()
    {
        console.log("AJAX request failed to: " + url);
        errorCallback(this);
    }
    ajax.open("POST", url, true);
    var formData = new FormData(formElem);
    ajax.send( formData );
}
////////////////////////////////////////////////////////////////////////////////
window.addEventListener('load', onDocLoaded, false);

function onDocLoaded(evt)
{
    byId('goBtn').addEventListener('click', onGoBtn, false);
}

var curIter = 0, maxIter=10;
function onGoBtn(evt)
{
    byId('numberIn').value = curIter;
    myAjaxPostForm('formAction.php', byId('mForm'), onAjaxDone);

    function onAjaxDone(ajax)
    {
        console.log(ajax.responseText);
        curIter++;
        if (curIter < maxIter)
        {
            byId('numberIn').value = curIter;
            myAjaxPostForm('formAction.php', byId('mForm'), onAjaxDone);
        }
    }
}
</script>
<style>
</style>
</head>
<body>
    <button id='goBtn'>GO!</button>
    <form id='mForm'>
        <input type='number' id='numberIn' name='numberIn'/>
    </form>
</body>
</html>

2. FormAction.php

<?php
    echo $_POST['numberIn'] . "\n";
?>

Upvotes: 0

snit80
snit80

Reputation: 731

Once the form is submitted, HTML page is basically refreshed and it means that that num will always be 1 and you will only submit 1 always. If you indeed need to submit but need to submit values from 1 to 100, then you will need to store the num value in a cookie before submitting each time and then increment the value by reading it from the cookie, that is the only way. Use the below functions to read and set cookie

var createCookie = function(name, value, days) {
var expires;
if (days) {
    var date = new Date();
    date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
    expires = "; expires=" + date.toGMTString();
}
else {
    expires = "";
}
document.cookie = name + "=" + value + expires + "; path=/";
}

function getCookie(c_name) {
if (document.cookie.length > 0) {
    c_start = document.cookie.indexOf(c_name + "=");
    if (c_start != -1) {
        c_start = c_start + c_name.length + 1;
        c_end = document.cookie.indexOf(";", c_start);
        if (c_end == -1) {
            c_end = document.cookie.length;
        }
        return unescape(document.cookie.substring(c_start, c_end));
    }
}
return "";
}

does that help?

Upvotes: 0

deviantxdes
deviantxdes

Reputation: 479

Try using SessionStorage, it stores the number even tho the page reloads.

$( document ).ready(function() {
        var num = 1000;
    if (!sessionStorage['currentNo']) {  
        sessionStorage['currentNo'] = 0;
    }

        if(sessionStorage['currentNo']<= num)
        {
          document.getElementById('numberIn').value=sessionStorage['currentNo'];
           sessionStorage['currentNo'] = sessionStorage['currentNo']+1;
          document.forms[0].submit();
        }

});

Upvotes: 0

Smeegs
Smeegs

Reputation: 9224

You've created an infinite loop.

You need to do num++ or num = num + 1 not just num+1

You're not incrementing the variable, you just calculating what num+1 is.

Upvotes: 2

Related Questions