Click on a link and display the value within an input

Asked

Viewed 140 times

1

Hello, does anyone know how I could do that, I have 10 link, each link corresponds to a type element link 1 = :D, link 2 = :S, link 3 = :$ and so on, there I have a input type="text" name="mensagem" placeholder="digite sua mensagem..."/>, my question is the following, as I would do for when the person clicked on one of these link the value that is informed on them showed in the input? without being by value="", I’ll illustrate it better <a href="javascript:void(0)">:D</a> <a href="javascript:void(0)">:S</a> <a href="javascript:void(0)">:$</a> by clicking on one of these link I want you to send the corresponding value ai link clicked to the input

2 answers

1


Create a eventListener with click for each <a>, that when clicked, the corresponding text will be concatenated to the text of the input:

document.addEventListener("DOMContentLoaded", function(){

   var els = document.body.querySelectorAll("a[href*='java']");
   
   for(var x=0; x<els.length; x++){
      
      els[x].addEventListener("click", function(){
         var a_txt = this.textContent,
              inpt = document.body.querySelector("#texto");
              
         inpt.value += " "+a_txt;
      });
   }

});
<a href="javascript:void(0)">:D</a>
<a href="javascript:void(0)">:S</a>
<a href="javascript:void(0)">:$</a>
<br />
<input id="texto" type="text" value="olá!" />

1

const 
    //O input
    input = document.getElementById('input'),  
    //Listener de quando clica
    clickListener = function(){
       input.value += this.innerText;
    };

document
   //a's filhos de .links-texto
   .querySelectorAll( '.links-texto a' )
   .forEach( function( e ){       
      //e = <a>
      e.addEventListener( 'click', clickListener );
});
<input id="input" type="text" />
<section class="links-texto">
  <a href="#">:D</a>
  <a href="#">:$</a>
  <a href="#">:)</a>
</section>

Browser other questions tagged

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