I don’t know why my JavaScript code is not responding when I click on the button

Please am new to programming and currently learning it on my own.
I wrote this JavaScript code but is not responding when I click the button.I don’t know why and the google chrome console is not showing any error. Please help me this is really frustrating me.

//UI variables 
    const WhatYouTyped = document.querySelector('#WhatYouTyped');
    const btn = document.querySelector('.btn');
    const ul = document.querySelector('.collection');

// Function
    loadEventFunction();

function loadEventFunction(){

  btn.addEventListener('submit', btnFunction);
}

function btnFunction(e){

  // If statement to check if the input is empty when the button is clicked

 if(WhatYouTyped.value === '') {
    alert('The input can\'t be empty');
  } 

// I created an li element and a text node to receive what ever that is put into the input.

  const li = document.createElement(li);
  li.className = 'collection-item';
  li.appendChild(document.createTextNode(WhatYouTyped.value));

  // I appended the list item to the ul

  ul.appendChild(li);

  WhatYouTyped.value === '';
  e.preventDefault();

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (</>) will also add backticks around text.

Note: Backticks are not single quotes.

markdown_Forums

  1. Use click instead of submit as the event for the button.

  2. createElement takes a string.

  3. Not sure if it was just missing when you posted the code but you have a missing closing bracket } for the btnFunction

https://jsfiddle.net/g3mczun9/

1 Like

Thanks for your reply, i don’t know how the codepen works but i have created a login and wrote my code there https://codepen.io/sylva-line/pen/MWwOXJV.

I wanted to create a code that accepts an input as a text node and display it as a child of the UL.

Thanks! I have changed the event to click but the order codes is still not working.

The Codepen you linked to is still using the submit event and not click. See my second point about createElement, you are not using it correctly.

Code changes needed:

// click event
btn.addEventListener('click', btnFunction);
// pass the string 'li'
const li = document.createElement('li');
1 Like