When the person chooses something in select display an image on the form side

Asked

Viewed 38 times

0

I am making a form in which the user will choose a background image, I wanted that when she chooses this image in select to display on the side or below a thumbnail of it, searched a lot on the internet but I found nothing that can help me. My form is very basic so far:

    <form action="gerador.php" enctype="multipart/form-data" method="POST">
  <fieldset>
    <legend style="text-align: center;">Gerador de banner</legend>
    <!--<legend><span class="number">1</span>E-mail:</legend>
    <input type="text" name="email">-->
    <legend><span class="number">2</span>Data:</legend>
    <input type="date" name="data">
    <legend><span class="number">3</span>Local:</legend>
    <input type="text" name="local" maxlength="78">
    <legend><span class="number">4</span>Horario:</legend>
    <input type="text" name="horario">
    <legend><span class="number">5</span>Background:</legend>
    <select name="bg">
        <option selected="" disabled="">Selecione o background...</option>
        <option value="bg1.png">Background 1</option>
        <option value="bg2.png">Background 2</option>
    </select>
    <legend><span class="number">6</span>Logo Universidade:</legend>
    <input name="arquivo" type="file" />
    <input type="submit" value="Gerar" />
  </fieldset>
</form>

Thank you in advance

  • 1 - Capture the event change of its element <select>; 2 - Search for the selected value; 3 - Create an element <img> (or select an existing DOM); 4 - Sets the value of src of the image as the selected value; 5 - Add the image to the DOM if it is not already in it. Want to try? Good luck.

  • I understood the logic, I was left with only 2 doubts, what is this DOM rs and how do I make to disappear the image if I choose another? I know I can give an Hide in the element, but in case I have 10 images I will have to give Hide in all at the end of the code?

  • vlw man, I will try to learn more about ajax and js because the latest projects is bone, Thank you

1 answer

0


Create an Event Listener in your select. Using change as a trigger, the callback function declared will be invoked every time the value of your select is changed. Then just change the source url of your element that contains the preview image.

document.getElementById('img_select').addEventListener('change', function() {
  document.getElementById('img_preview').src = this.value
})
<select name="bg" id="img_select">
    <option selected disabled>Selecione o background...</option>
    <option value="https://opengameart.org/sites/default/files/backgrounddetailed3.png">Background 1</option>
    <option value="https://opengameart.org/sites/default/files/backgrounddetailed1.png.preview.jpg">Background 2</option>
</select>
<img id="img_preview">

  • gave right to what I needed, saved me, Brawl.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.