mardi 5 avril 2016

for loop with if else not working Javascript

I'm trying to make a list where users can insert their favourite beer. there have to be a check if the "userinput" is already in the array.. My thoughts were as follows: loop through the beersArray and check if there is a value in the array that is the same as what user puts in. If there is, alert and do not add. If not, then add the user input to a list item.

var submitBier = document.getElementById("submitbeer");
submitBier.addEventListener("click", function(){
    event.preventDefault();
    var beersArray = [];
    var beer = document.getElementById("favobeer");
    var beerList = document.getElementById("listwithbeer");
    var beerLi = document.createElement("LI");
    var BeerName = document.createTextNode(beer.value);

    var i;
    var j;
    for (j = 0; j < beersArray.length; j++) {
        if (beersArray[j] === beer.value) {
            alert("This beer is already in the list");
        } else {

            for (i = 0; i < beersArray.length; i++) {
                beersArray[i].className = 'beer';
                beerLi.appendChild(BeerName);
                beerList.appendChild(beerLi);
                beersArray.push(beerList.appendChild(beerLi));
            }
        }
    }
});
<div class="beers">
    <h1 id="vraagnaam">add your favourite beers</h1>
    <input type="text" id="favobeer"  value = "" />
    <button id="submitbeer" type="submit" value="Submit" >add</button>
    <ul id="listwithbeer"></ul>
</div>

Aucun commentaire:

Enregistrer un commentaire