简体   繁体   中英

ES6 push and bind to an array

Please pardon my newbie verbiage here while I attempt to explain my problem (also I did search and came up with nothing, I'd also like to use ES6, not jQuery)

I'm trying to have a text input that when entered it's pushed into an empty array. When more input is entered in, I would like to have that bound to the array as well.

So I have it working, kinda. I can get one thing in the array but I can't seem to anything else to go in there. Here's what I have so far:

My html:

<input type="text" class="theplayer pre" name="Player" id="bind" placeholder="Enter Names" onclick='javascript: this.value = ""' />

My JS:

    let namesOfPlayers = [];
    const currentValue = document.getElementById("bind").value;
    namesOfPlayers.push(currentValue);
    //I don't know how to add in another text/value here
    console.log('namesOfPlayers', namesOfPlayers);

I don't know if I'm supposed to be doing a for each here or if there's a way to bind another value into the array.

Thanks and much appreciated for letting me try to clumsily explain this.

You can include <input type="button"> element as sibling of <input type="text"> element. At click on <input type="button"> .push() .value of <input type="text"> to array

 <input type="text" class="theplayer pre" name="Player" id="bind" placeholder="Enter Names" /> <input type="button" value="click" /> <script> let namesOfPlayers = []; let input = document.getElementById("bind"); let button = input.nextElementSibling; button.addEventListener("click", function() { namesOfPlayers.push(input.value); console.log(namesOfPlayers); }); </script> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM