Home > Back-end >  How to print a function using a click event
How to print a function using a click event

Time:01-10

I am doing the Print all even numbers from 0 – 10 challange, I created a funciton that should take a usuers input and give the even number of it, if it's 10, 100, 1000, 10 000 etc.

I am trying to get the user input to print from the array by using an event listener, that when submit button is clicked, all numbers are printed in the outcome html element

 <form id="form">
   <input  type="text">
   <input  type="submit">
 </form>

 <div >
   <p>Output</p>
   <div ></div>
 </div>
//Empty Array
arrayEvenNum = []

/function that loops through input value and push to array
function loopInput(){
    let userInput = document.querySelector(".input").value

    for (let i = 0; i <= userInput; i =2) {
       arrayEvenNum.push(i)
    }

    return userInput

}

let submit = document.querySelector(".submit")

submit.addEventListener("click",() => {
    //print numbers in array in HTML

})

CodePudding user response:

If you want to add the text to the 'outcome' div, get the div as an element and add text to it - here is one way to do this within your submit event listener callback:

// This method returns an array of elements, get the first one
const outcome = document.getElementsByClassName("outcome")[0]; 

// Create a text node containing your results:
const textNode = document.createTextNode(arrayEvenNum.toString());

// Append the text node to the div
outcome.appendChild(textNode);
  • Related