Arkhall Arkhall - 18 days ago 6
HTML Question

Javascript - Empty nodes issue

I'am learning about using nodes and I have a little issue, then I don't konw why it doesn't work.

https://jsfiddle.net/Lrzy0263/

HTML

<input type="text" id="couleur">
<button id="ajouter">Ajouter</button>
<ul id="liste"></ul>


Javascript

document.getElementById("ajouter").addEventListener('click',
function (){
var couleur = document.getElementById("couleur").value;
var li = document.createElement("li");
var texte = document.createTextNode(document.getElementById("couleur").value);
li.appendChild(texte);
document.getElementById("liste").appendChild(li);
document.getElementById("couleur").value = "";
document.getElementById("couleur").focus();
if(couleur.length == 0){
return false;
}
}
)
document.getElementById("liste").addEventListener('click',
function(e){
document.getElementById("liste").removeChild(e.target);
}
)


The problem is when the input is empty and when I click to add an "li", it continues to add empty "li" O_o

How can I stop the event ? I already have the condition when the length = 0 but it doesn't work if I only return false.

If you have some ideas, I am open with it =)

Have a nice day

Answer

Your if statement that checks if the length is zero is at the end of your function. Returning false doesn't cancel code that has already run; you have to return before the LI gets added. Move that if statement to the top of the function, like so:

document.getElementById("ajouter").addEventListener('click',
    function (){
        var couleur = document.getElementById("couleur").value;
        if(couleur.length == 0){
            return false;
        }
        var li = document.createElement("li");
        var texte =       document.createTextNode(document.getElementById("couleur").value);
        li.appendChild(texte);
        document.getElementById("liste").appendChild(li);
        document.getElementById("couleur").value = "";
        document.getElementById("couleur").focus();
    }
)