开发者

Pass HTML form entries into a Javascript array to then be written to a client side cookie?

I'm building a bit of a test-case JS application, something very basic, but have run into some problems.

I开发者_StackOverflow社区'm trying to use a HTML form for a user to enter a number, which is then written to a Javascript Array. The user then has the option to write that same array to a local (client side) cookie. (I understand the security implications of this - it's a test-case and not for commercial use.)

However, I can't make the connection - how can I capture the HTML entry, press 'submit' which will send it to a JS array, where the user can then press a different 'submit' which will write the array to a text file?

If anyone can help I'd appreciate it because it's been nearly 6 hours and it's not funny anymore.


To read the data, use code such as this:

var data = new Array;

function readData() {
    var inputs = document.getElementsByTagName('input');
    for (i in inputs) {
        if (!isNaN(i - 0) && inputs[i].type == 'text') {
            data[i - 0] = inputs[i].value;
        }
    }
}

Trigger it with a button input:

<input type="button" onclick="readData();" value="Read" />

Still, do you want it as a cookie, a text file or what? Here are a few possible statements to use depending on which you want:

alert(data.toString());
window.location.href = 'data:text/plain,' + escape(data.toString());
document.cookie = 'data=' + data.toString();

The second one generates plain text that will likely be displayed in the browser. To save it as a text file, you'll have to either

  • do it manually after generating it
  • use some MIME type such as application/octet-stream instead of text/plain (then the user will have to name the file manually).


on the form add

   <form bla bla bla onsubmit="return catchThings()">
      <input name="test" id="test">
   </form>

the with the javascript you can do

function catchThings(){
     // get all the forms inputs by id
     // do things with arrays or whatever
     var example = document.getElementById("test").value;
     return false;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜