Image change as the form field is chosen

Asked

Viewed 31 times

1

I want when I select, for example, the option Ches replaces where it is NOME automatically in HTML.

.goleiro-1 {
    height: 70px;
    width: 70px;
    background-color: #fff;
    border-radius: 50%;
    box-shadow: 0 4px 1px 0 rgba(0,0,0,.5);
    margin-left: 42%;
    margin-top: 25px;
    float: left;
    position: relative;
}

.s_goleiro-1 {
    float: left;
    margin-left: 38%;
    margin-top: 5px;
    position: relative;
    border: none;
    border-radius: 4px;
    padding: 6px;
    font-size: 16px;
}
<img class="goleiro-1" src="http://meusite.com/avatar.php?user=NOME" data-toggle="tooltip" data-placement="top" title="Goleiro"> 
<select class="s_goleiro-1" name="goleiro">
  <option value="PetCech">PetCech</option>
  <option value="Ches">Ches</option>
  <option value="Drionn">Drionn</option>
  <option value="TPB">TPB</option>
</select>
</div>

1 answer

2


    var select = document.querySelector('.s_goleiro-1');
    var nome   = document.querySelector('.goleiro-1');
    
    select.addEventListener('change',function(){
        nome.src =  'http://meusite.com/avatar.php?user='+select.value;
        nome.title = select.value;
    })
    .goleiro-1 {
        height: 70px;
        width: 70px;
        background-color: #fff;
        border-radius: 50%;
        box-shadow: 0 4px 1px 0 rgba(0,0,0,.5);
        margin-left: 42%;
        margin-top: 25px;
        float: left;
        position: relative;
    }

    .s_goleiro-1 {
        float: left;
        margin-left: 38%;
        margin-top: 5px;
        position: relative;
        border: none;
        border-radius: 4px;
        padding: 6px;
        font-size: 16px;
    }
    <img class="goleiro-1" src="http://meusite.com/avatar.php?user=NOME" data-toggle="tooltip" data-placement="top" title="Goleiro"> 
    <select class="s_goleiro-1" name="goleiro">
      <option value="PetCech">PetCech</option>
      <option value="Ches">Ches</option>
      <option value="Drionn">Drionn</option>
      <option value="TPB">TPB</option>
    </select>

  • It seems to me that the intention was not to change the title image, only the src.

  • @Sam This is just for the boy who asked the question can see it working ;)

  • It worked perfectly, but I have 3 other fields in the form: defender-1, half-1, striker-1. How do I for all?

  • @Thiagovinicius had to have informed this in the question, now it was rs... unless Douglas here wants to reformulate the answer, but the question has already been answered.

  • Ah, what a pity then :/

  • @Thiagovinicius I will make an answer and send you.

  • Okay, thank you very much

  • Taí: https://jsfiddle.net/34s15xvh/ .... note that there has been a change in CSS to be generic and HTML has added classes "avatars" and "players".

  • Thanks a lot, Sam. It worked out just fine.

Show 4 more comments

Browser other questions tagged

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