如何使用html5本地存储显示用户输入列表?

时间:2013-12-27 12:48:01

标签: javascript html5 forms local-storage local

我正在创建我的第一个html5网络应用,它记录了用户的体重进度。目前我有一个简单的表格打印下面的输入。我希望它保存在本地存储中,我还希望能够添加更多输入并将其显示在表格中。请有人帮我这个吗?我有点像新手。

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Home Fitness</title>
<link type="text/css" rel="stylesheet" href="styles.css" />

<script>
    function display(form){
        form.o_weight.value = form.weight.value;
    return false;
    }
    </script>


    </head>

    <body>
<header>
    <h1>Weight Tracker</h1>
</header>

    <article>
<h2>Weight Input</h2>
    <p>Please enter your current weight below and submit.</p>
    </article>

<form name="input" action="" method="get" onsubmit="return display(this);">

    <section>

    <p>Weight:</p><input type="text" name="weight">
    <input type="submit" value="Submit">

    </section>

    <section>       
      <table>

    <th>Weight</th>

    <tr>
    <td><output name="o_weight" style="width:100px; height:20px"></output></td>
     </tr>
      </table>

    </section>

    </form>

        <nav>
            <ul>
                <li><a href="index.html">home</a></li>
            </ul>
        </nav>

        <footer>

        </footer>   

2 个答案:

答案 0 :(得分:0)

您可以这样做:

function display(form){
    //get all form elements
    var elements = form.elements;
    //loop through the elements
    for(var i = 0; i< elements.length; i++){
        //store every item individually
        localStorage.setItem(elements[i].name, elements[i].value);
    }
}

使用以下内容检索值:

var weigth = localStorage.getItem('weight');//input with name "weigth"

答案 1 :(得分:0)

将权重与其他表单元素一起存储在localStorage中作为字符串化对象 将密钥作为当前日期。

第1步:获取表单元素

function getFormElementValues("formName"){
 //get hold of form and get the corresponding values into Object
}  

上面的函数应该返回带有表单元素标签的Object及其值。

e.g 
 {
  weight: 100,
  unit : "KG",
  breadsYouAte:3
} 

步骤2:将当前时间作为键并放入对象

function addCurrentTime(formObject){
  var d = new Date();
  var dString = d.getTime(); 
  return {dString : formObject}
}

第3步:存储到localStorage

function StoreObject(objectWithTime){
  var formString = JSON.stringify(objectWithTime);
  if(localStorage['formName']){
    //this will get executed only for first time
    localStorage['formName'] = [formString];
  }else{
    var arrayString = JSON.parse(localStorage['formName']);
    arrayString.push(formString);
  }
}

步骤4:执行在3个步骤中创建的辅助函数

var form = getFormElementValues("formName")
var formTimeObject = addCurrentTime(form)
var store = storeObject(formTimeObject)