0

I have a trouble here when I press the SAVE INPUT button. I want that when I enter the text inside the box, and then click to SAVE INPUT, the output will be the value that I entered (I initialized an array and it worked), but when I do not put anything in the textbox, and click SAVE INPUT, it will return <li> element symbol. How can I make the code break when I do not enter anything? Here is my code:

const inputBtn = document.getElementById("input-btn")
const inputEl = document.getElementById("input-el") 
const ulEl = document.getElementById("ul-el")
let myLead = []

inputBtn.addEventListener("click", function() {
        myLead.push(inputEl.value)
        renderLoad()
        inputEl.value = "" 

});

function renderLoad() {
    let listItems = "";
    for (let i = 0; i < myLead.length ; i++ ) {
        /* listItems += "<li><a href='#'' target='_blank'>" + myLead[i] + "</li>"; */
        listItems += `
        <li>
            <a href='#' target='_blank'>${myLead[i]}  
        </li>`;
        ulEl.innerHTML = listItems   // follow html rule 
    }
}

e.g. case 1: input with value (My code worked!)

input: "www.google.com"
output:

  • www.google.com
  • case2: input with no value

    input:
    output:
    (My code does not work with this case! Output shows me "

  • " symbol each time I click SAVE INPUT)
    • Does this answer your question? [JavaScript validation for empty input field](https://stackoverflow.com/questions/3937513/javascript-validation-for-empty-input-field) – pilchard Mar 18 '23 at 01:09
    • or [How to prevent an empty string or null ("") value from being appended when pushing data into an array?](https://stackoverflow.com/questions/47780856/how-to-prevent-an-empty-string-or-null-value-from-being-appended-when-pushi) – pilchard Mar 18 '23 at 01:12

    1 Answers1

    1

    You can use trim to remove all leading and trailing whitespace from a string. If the value is empty after trimming, then there were only whitespace characters (or no characters) entered, so don't add it to the array.

    if (inputEl.value.trim()) myLead.push(inputEl.value)
    
    Unmitigated
    • 76,500
    • 11
    • 62
    • 80