How to take the value of a tag and send it to another tag with js

Asked

Viewed 411 times

1

Hi, guys, I’m having a problem.

I have 4 equal tags, but I want to send the value of the tag that was clicked to the value of the input.

Example :

<img id="imgs" src="img_01">
<img id="imgs" src="img_02">
<img id="imgs" src="img_03">
<img id="imgs" src="img_04">
<input type="text" nome="selecionar_img" value="">

Suppose I click on the img of src 3, I need my input this way.

<input type="text" nome="selecionar_img" value="img_03">

And if I click another img tag the value field delete the previous value and put the new value of the tag that was clicked.

    <input type="text" nome="selecionar_img" value="img_03"> // Valor anterior
    <input type="text" nome="selecionar_img" value="img_01"> // Novo Valor passado

I thank anyone who can help me, I have no experience with Js but I need to do these events. obg ^-^

1 answer

0


First of all, two observations: all your tags img have the same value in the attribute id. According to the specification html, the value of that element must be unique. These values should be in the attribute class. In addition, the name of the attribute in input is name and not nome.

So your tags would look like this:

<img class="imgs" src="img_01">
<img class="imgs" src="img_02">
<img class="imgs" src="img_03">
<img class="imgs" src="img_04">
<input type="text" name="selecionar_img" value="">

To fill the input with the attribute src image, you can do it this way:

$(document).ready(function(){
    $(".imgs").click(function(){
        $("input[name=selecionar_img]").val($(this).attr('src'));
    });
});
  • Sorry, by html I just typed here, I didn’t get the code I’m doing was just to make a shallow example msm, but js worked perfectly the way I wanted. obg for the help

  • @Delacroix, no problem. As some novice may have some similar doubt and fall on this page, I evidenced these mistakes to prevent someone from reproducing them.

Browser other questions tagged

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