1

Am able to store one text box to local storage via a button. How would I go about allowing it to take in all the text boxes I have in my 'survey'? Create id's for each text box then listing them all out within the get/set of my js?

<label for="serveri"> Server: </label> <input type='text' name="server" id="saveServer"/> <button onclick="saveData()" type="button" value="Save" id="Save">Save</button>

    var save_button = document.getElementById('Save')
save_button.onclick = saveData;
function saveData(){
  var input = document.getElementById("saveServer");
  localStorage.setItem("server", input.value);
  var storedValue = localStorage.getItem("server");
}

To get a better understanding(all text boxes), here is the whole in JSfiddle:http://jsfiddle.net/BDutb/

4

1 回答 1

0

If you use a library like jQuery you can get the elements and loop through the values very easily. If you want the localStorage variables names to make sense then assign the input fields names and you can do:

See my example here: http://jsfiddle.net/spacebean/BDutb/11/

$('form').submit(function() {
  $('input, select, textarea').each(function() {
   var value = $(this).val(),
       name = $(this).attr('name');
   localStorage[name] = value;
  });   
});

I shortened the form for demo sake, but you should be able to take it from there.

Edit: updated fixed jsFiddle link.

于 2013-10-23T14:22:59.847 回答