在javascript数组中存储用户输入并显示它

时间:2016-04-19 13:09:43

标签: javascript jquery arrays

我必须使用javascript和jquery从表单中获取用户输入并将其保存到日志中,然后由用户调用。

我的想法是首先将用户输入存储在一个数组中。我已经能够通过1次输入成功完成这项工作,但我对多次输入没有运气。

var d = new Date();
var arr = [];

var arr = document.getElementById("conductivity").value;
document.getElementById("demoX").innerHTML = arr;


function myX() {
    arr.push(d + conductivity.value);
    document.getElementById("demoX").innerHTML = arr;

如何存储多个字段? (比如电导率+电压+ blah)

编辑:我原本说我希望它以字符串形式返回。为了澄清,我想在新页面中显示这些内容: 19/04/2016电导率:42,电压:11,Blah:0

1 个答案:

答案 0 :(得分:1)

您可以创建一个对象(避免除了它之外的全局变量),然后在其中存储内容,包括您需要使用的函数(命名空间)!

您可以尝试一下:https://jsfiddle.net/MarkSchultheiss/bacy1r18/1/

示例加价:

Cond:
<input id="conductivity" value="100" /> Blah
<input id="blah" value="bluesblah"> Volt
<input id="voltage" value="100" /> Date
<input id="mydate" type="date" />
<button id="save" type="button">
  save
</button>
<button id="show" type="button">
  show
</button>
<div id="demoX">
</div>

<强>代码:

var myThings = myThings || {}
myThings.values = {
  outputs: [],
  labels: {
    d: "",
    c: "Conductivity",
    v: "Voltage",
    b: "Blah"
  },
  defaultDate: new Date()
};
myThings.library = {
  formatdate: function(mydate) {
    var d = new Date(mydate);
    var day = d.getDate();
    var month = d.getMonth() + 1;
    var year = d.getFullYear();
    return day + '/' + month + '/' + year;
  },
  saveEm: function() {
    var cond = document.getElementById("conductivity").value;
    var volt = document.getElementById("voltage").value;
    var blah = document.getElementById("blah").value;
    // default to now date
    var d = document.getElementById("mydate").value ? document.getElementById("mydate").value : myThings.values.defaultDate;

    myThings.values.outputs.push({
      d: myThings.library.formatdate(d),
      cond: cond,
      volt: volt,
      blah: blah
    });
  },

  showEm: function() {
    var arout = "";
    for (var i = 0; i < myThings.values.outputs.length; i++) {
      arout += "<div class='outrow'>";
      arout += "<span class='lab'>" + myThings.values.labels.d + "</span>";
      arout += "<span class='outv'>" + myThings.values.outputs[i].d + "</span>";
      arout += "<span class='lab'>" + myThings.values.labels.c + "</span>";
      arout += "<span class='outv'>" + myThings.values.outputs[i].cond + "</span>";
      arout += "<span class='lab'>" + myThings.values.labels.v + "</span>";
      arout += "<span class='outv'>" + myThings.values.outputs[i].volt + "</span>";
      arout += "<span class='lab'>" + myThings.values.labels.b + "</span>";
      arout += "<span class='outv'>" + myThings.values.outputs[i].blah + "</span>";
      arout += "</div>";
    }
    var demo = document.getElementById("demoX");
    demo.innerHTML = arout;
  }
};
var show = document.getElementById("show");
show.addEventListener("click", myThings.library.showEm);
var save = document.getElementById("save");
save.addEventListener("click", myThings.library.saveEm);