Change image when selecting radio in form

Asked

Viewed 553 times

0

Good evening, I’ll provide an image and the code. I don’t know how, and I’d like to learn. NOTE: I don’t want the image to change when I submit the form, I want it to change right after I click on the option! Ao clicar no input do lado esquerdo, TROCAR a imagem do lado direito

Formlarium

<form method="POST" action="escalar.php">
<label>Escolha o Goleiro</label><br>
<input type="radio" name="gol" value="Milk"> anderson<br>
<input type="radio" name="gol" value="Butter" checked> davi<br>
<input type="radio" name="gol" value="Cheese"> paulo
<label>Escolha o Tecnico</label><br>
<input type="radio" name="tec" value="Milk"> maikon<br>
<input type="radio" name="tec" value="Butter" checked> dunga<br>
<input type="radio" name="tec" value="Cheese"> kleber
</form>

Imagery

<img src="/componentes/circulo.png" alt="goleiro" style="width: 16%; height:8%; position:relative; margin-top:-125px; margin-left:180px;" />  

From now on, thank you

  • 1

    Where are you getting these images?

  • in my server folder. /components/circle.png /components/goalkeeper.png

  • And this value inputs are serious or should be circulo, goleiro etc... ? (the names of the respective images)

  • I changed the code.

  • But it can also be the name of the image, if easy in the code.

  • Well, it seems to me that you are trying to change the image in real time by radio, which with php is not possible to do, because the information in php has to go through the server, so you would need to send the form, if you want to change the image at the time of the click, should use javascript then.

Show 1 more comment

2 answers

1


Well, I want to thank everyone who tried to help me. I managed to solve the problem in the EASIEST way possible. It was really easy, I will pass as I did, but I will not explain, the code is so easy that even beginners (like me) can understand at first.

Code js:

<script type="text/javascript"> 
function alterarImagem(objeto, caminhoNovaImagem) {
document.getElementById(objeto).src = caminhoNovaImagem;
}
</script>

HTML code:

<input type="radio" onclick="alterarImagem('gol', '/componentes/campo.png');" name="group1" value="Milk"> Milk<br>
<img src="/componentes/circulo.png" alt="goleiro" id="gol" style="width: 16%; height:8%; position:relative; margin-top:-125px; margin-left:180px;" />

Like I said, it’s pretty simple!

  • 1

    Note: The mouse pointer is not the only one that can be used to change the state of the input[type=radio], can also be used keyboard. For example, just focus on the input[type=radio] and press a directional/vertical key as or v and will check the input[type=radio] previous or next.

  • 1

    You can create several legal systems like this ^^

1

Code explained:

 // Seu formulário
var form = document.getElementsByTagName('form')[0],

 // Todos input[type=radio] com o nome "gol"
    goalkeeper = form.gol,

 // Todos input[type=radio] com o nome "tec"
    trainer = form.tec;

/**
 * Evento estilo-onchange para vários input[type=radio].
 *
 * @param array list
 * @param function callback
 */
function addRadioChangeEvent(list, callback)
{
    // Função que executa quando um input é provavelmente checado
    // usando onkeydown, onclick, etc.
    var fnc = function(e)
    {
        // Pega a índice do input[type=radio]
        for(var i = 0, el; el = list[i]; i ++)
        {
            if(el === e.target) break;
        }

        // Checa se o input foi checado e se não é igual
        // ao checado anteriormente
        if(el.checked && checked !== i) {
            // Memoriza o input checado
            checked = i;
            // Executa a função no segundo parâmetro já que o
            // input foi modificado, e traz seu valor, e.g:
            // "Milk", no 1st parâmetro
            if(typeof callback === 'function') callback(el.value);
        }

    }, checked = NaN;

    // Memoriza o input checado atualmente
    (function()
    {
        for(var i = 0, el; el = list[i]; i ++)
        {
            if(el.checked) {
                checked = i;
                break;
            }
        }

    })();

    // Eventos usados em cada input
    var evt = ['click', 'keydown', 'keyup'];

    function addEvts(c)
    {
        // Percorre cada input
        for(var b = 0, el; el = list[b]; b ++)
        {
            // Percore cada string na tabela 'evt'
            for(var i = 0, e; e = evt[i]; i ++) c(el, e);
            // E chama o callback ('c') para cada input com uma string do 'evt'
        }
    }

    // Checa se o addEventListener é suportado pelo navegador
    if(typeof (window['Element'] || window['HTMLElement'])['prototype']['addEventListener'] === 'function')

        addEvts(function(el, e) { el.addEventListener(e, fnc) })

    // Se addEventListener não for suportado, usa o attachEvent em vez
    ;else

        addEvts(function(el, e) { el.attachEvent('on' + e, fnc) })
    ;
}

// Pega a sua imagem
var img = document.getElementsByTagName('img')[0];

// Adiciona o evento estilo-onchange para os input[type=radio] que
// que definem o goleiro.
addRadioChangeEvent(goalkeeper, function(value) {

    switch(value)
    {
        case "Milk":
            img.src = "?"; // imagem 1 ?
            break;

        case "Butter":
            img.src = "?"; // imagem 2?
            break;

        default: // "Cheese"
            img.src = "?"; // imagem 3?

    }

});

// Adiciona o evento estilo-onchange para os input[type=radio] que
// que definem o técnico.
addRadioChangeEvent(trainer, function(value) {
    // ?
});
  • 1

    I’ll try, thank you. But still I’ll save more manners.

Browser other questions tagged

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