Loading link on the same page, no refresh! [duplicate]

0

Good evening, good evening

I need some help for something that seems very simple but I did not find anything on the net that could be applied. Well, come on:

I need the contents of a link to be shown in an input field on the same page, without refresh!

Simply put, the page code:

<!DOCTYPE html>
<html>
<head>
    <title>Exemplo</title> 
</head>
<body>    
     <a href="#">Valor1</a>
     <a href="#">Valor2</a>
</body>

<input type="text" value="<?php echo "Escrever o valor do link que foi clicado!"?>">

</html>
    
asked by anonymous 17.07.2016 / 23:19

1 answer

1

This can be done using JavaScript . I do not know what your level of knowledge is with JavaScript however I am the kind of guy who likes to explain piece by piece: D

jQuery

$('a').click(function () {
  $('input').attr('value', $(this).text());
});

The above code creates a click event on all the <a> tags of the page (I do not really recommend this, as the right one would be to create a ID > for the anchors from which the content will be added to the value attribute of the <input> tag.)

When the user clicks on the anchor, the event will search for all the inputs on the page and add the value attribute corresponding to the $(this) value of the anchor.

HTML

<body>    
  <a href="#">Valor1</a>
  <a href="#">Valor2</a>
  <input type="text">
</body>
  

I do not want to be boring with this but you put the tag <input> out of <body> this is not good practice.

If you want to take a look at this link link to see the above code running.

Update

I made this modification using Classes . Because? Well I imagine you want to get the value of a set of anchors right? Using ID you violate a unitary concept (so to speak).

How so unitary?

The ID is a unique selector type, which can not be repeated from your declaration, in other words if you set an ID to the Value 1 you can not repeat it in Value 2 .

That's where Classes come in, with this selector you can repeat endless times in different tags without violating such a concept.

  

Remembering that this term "unitary" is not explicitly documented by W3C , I just used it for educational purposes.

    
17.07.2016 / 23:53