将用户输入插入数组

时间:2015-11-12 21:17:50

标签: arrays input

我今天的HTML / JS文件出现了这个问题,我试图让脚本正常运行。

HTML:               

<head>
    <h1>Pushing into an array</h1>
</head>
    <body>

    <p>Enter your input to the form before adding</p>

    <p>Click to add to array</p>
    <p id="demo"></p>

    <br>

    <button onclick="myFunction()">Display Variable</button>

    <form name="myform"> 
    <input type="text" name="text1" value=""> 
    <input type="button" value="Enter Value" onclick="setValue()"> 
    </form>  

    <p id="value"></p>

</body>

JavaScript的:

var colours = ["Red", "Orange", "Yellow", "Green"];
document.getElementById("myFunction").innerHTML = colours;

function display() {
colours.push("Blue");
document.getElementById("demo").innerHTML = colours;
}

function setValue(){ 
var myVariable = document.forms["myform"]["text1"].value;
document.getElementById("value").innerHTML = myVariable;
} 

这样做的目的是从表单/警报中获取用户输入并将其传输到阵列(显示在屏幕上)但我似乎无法使其正常工作!有什么想法吗?

3 个答案:

答案 0 :(得分:0)

myFunction()的onclick可能应该是display(),而document.getElementById(&#34; myFunction&#34;)目前还没有引用页面中任何元素的id,如果这是& #39;演示&#39; (不确定您是否尝试将数组设置为页面中的某个元素)?

答案 1 :(得分:0)

我不确切地知道你想做什么,但是根据我的直觉,我修改了代码来做我认为你问的事。

HTML

<body>

<p>Enter your input to the form before adding</p>

<p>Click to add to array</p>
<p id="demo"></p>

<br> 
<div id="myFunction"></div>

<button onclick="display()">Display Variable</button>

<form name="myform"> 
<input type="text" name="text1" value=""> 
<input type="button" value="Enter Value" onclick="setValue()"> 
</form>  

<p id="value"></p>

的JavaScript

var colours = ["Red", "Orange", "Yellow", "Green"];

function display() {
   document.getElementById("demo").innerHTML = colours;
}

function setValue(){ 
   var myVariable = document.forms["myform"]["text1"].value;
   document.getElementById("value").innerHTML = myVariable;
   colours.push(myVariable);
} 

添加值,点击输入值,然后点击显示变量。你已经列出了它。

这是the code on CodePen

答案 2 :(得分:0)

我设法通过帮助排序代码。谢谢,修复:

<!DOCTYPE html>

<html>

<head>
    <script>
        var colours = ["Red", "Orange", "Yellow", "Green"];

        function display() {
           document.getElementById("demo").innerHTML = colours;
        }

        function setValue(){ 
           var myVariable = document.myform.text1.value;
           document.getElementById("demo2").innerHTML = myVariable;
           colours.push(myVariable);
        }
    </script>
</head>

<body>

    <p>Enter your input to the form before adding</p>

    <p>Click to add to array</p>
    <p id="demo"></p>

    <br> 
    <div id="myFunction"></div>

    <button onclick="display()">Display Variable</button>

    <form name="myform"> 
    <input type="text" name="text1" value=""> 
    <input type="button" value="Enter Value" onclick="setValue()"> 
    </form>  

    <p id="demo2"></p>

</body>
</html>