skip to Main Content

i wanted to create a webpage for creating memes as a fun project.

so far, i am attempting to add a new image element to the body of the document via JS using the url that is entered into the label with input type of url, but the image does not seem to load

//via the code below, i was expecting the actual image of the url to appear on the webpage after appending the image element to the dom but that does no seem to be the case

const form = document.querySelector('#form');
form.addEventListener('submit', function (e) {
    e.preventDefault();
    const newImage = document.createElement('img');
    const newImageValue = 
    document.querySelector('#imageLink').value;

    if (newImageValue === '') {
        alert('Please enter a URL');
        return;
    }

    newImage.src = newImageValue;
    newImage.alt = 'Meme Image';
    document.body.appendChild(newImage);
    document.querySelector("imageLink").reset;
});

2

Answers


  1. It looks like you are missing the # here document.querySelector("imageLink").reset when selecting the code which causing the code to break

    const form = document.querySelector('#form');
    form.addEventListener('submit', function(e) {
      e.preventDefault();
      const newImage = document.createElement('img');
      const newImageValue =
        document.querySelector('#imageLink').value;
    
      if (newImageValue === '') {
        alert('Please enter a URL');
        return;
      }
    
      newImage.src = newImageValue;
      newImage.alt = 'Meme Image';
      document.body.appendChild(newImage);
      document.querySelector("#imageLink").reset;
    });
    <form id="form">
      <input id="imageLink">
      <button type="submit">Submit</button>
    
    
    </form>
    Login or Signup to reply.
    1. Reset is type of function to reset the form that is being submited, you should call like this reset()
    2. Use new FormData() efficiently, does not need any query selector again.
    const form = document.getElementById('form');
    const memes = document.getElementById('memes');
    form.addEventListener('submit', function (e) {
        e.preventDefault();
        let f = new FormData(e.target);
        let url = f.get("url");
        const newImage = document.createElement('img');
        if (url === '') {
            alert('Please enter a URL');
            return;
        }
    
        newImage.src = url;
        newImage.alt = 'Meme Image';
        memes.appendChild(newImage);
        e.target.reset();
    });
    section{
      padding:1rem;
    }
    <form id="form">
      <label for="url">Enter an https:// URL:</label>
    
      <input type="url" name="url" id="url"
           placeholder="https://example.com"
           pattern="https://.*" size="30"
           required>
       <button>Add</button>
    </form>
    <section id="memes">
    
    </section>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search