如何存储在数组中并显示它们

时间:2017-03-24 09:05:50

标签: javascript html

<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8" />
  <h1>Lab 4 Exercise 2</h1>
</head>

<body>
  <form id="recordform">
    <p><i>Please complete your registration</i></p>
    <fieldset>
      <legend>Person Register</legend>
      <label for="icno">IC No </label>
      <input type="text" id="icno" size="20" placeholder="E.g810312102121">

      <label for="name">Name </label>
      <input type="text" id="name" size="45"><br/>

      <button type="button" id="submit">Add Record</button>
      <button type="button" id="display">Display Records</button><br/>
    </fieldset>
  </form>

  <script>
    var inputArray = [];
    var input1 = document.getElementById("icno");
    var input2 = document.getElementById("name");
    document.getElementById("submit").addEventListener("click", myfunction);

    function myfunction() {
      inputArray.push(input1.value);
      inputArray.push(input2.value);
      alert("Thanks for submitting");
    }

    document.getElementById("display").onclick;

    function function2() {
      alert("These are the list of records");
    }
  </script>
</body>

</html>

当用户点击添加记录按钮时,我正在尝试将输入值存储到数组中。

当用户点击显示记录按钮时,想要使用提醒消息获取并显示记录。

1 个答案:

答案 0 :(得分:0)

这是一个解决方案。

  1. 当用户点击添加记录时,将输入元素的值转换为input1input2
  2. 使用索引显示inputArray的值。请查看此链接以获取更多信息 - https://www.w3schools.com/js/js_arrays.asp
  3. &#13;
    &#13;
    <!DOCTYPE html>
    <html>
    
    <head>
      <meta charset="utf-8" />
      <h1>Lab 4 Exercise 2</h1>
    </head>
    
    <body>
      <form id="recordform">
        <p><i>Please complete your registration</i></p>
        <fieldset>
          <legend>Person Register</legend>
          <label for="icno">IC No </label>
          <input type="text" id="icno" size="20" placeholder="E.g810312102121">
    
          <label for="name">Name </label>
          <input type="text" id="name" size="45"><br/>
    
          <button type="button" id="submit">Add Record</button>
          <button type="button" id="display">Display Records</button><br/>
        </fieldset>
      </form>
    
      <script>
        var inputArray = [],
          input1,
          input2;
        document.getElementById("submit").addEventListener("click", myfunction);
        document.getElementById("display").addEventListener("click", displayrecords);
    
        function myfunction() {
          input1 = document.getElementById("icno").value;
          input2 = document.getElementById("name").value;
          inputArray.push(input1, input2);
          alert("Thanks for submitting");
        }
    
        function displayrecords() {
          alert("Input 1: " + inputArray[0] + "\nInput 2: " + inputArray[1]);
        }
      </script>
    </body>
    
    </html>
    &#13;
    &#13;
    &#13;

相关问题