Select Textarea Text with Variables on Click

Asked

Viewed 99 times

0

In the case below:

Select textarea text by clicking

If I want an example1 variable, example2, exampleN. As I declare in jQuery? I can’t do it like this...

 $(document).on('click', 'input[type=text][id=valor_unitario"+id+"]', function() {
     this.select();

Correct?

And how do I insert into jQuery more than one input(e.g.: exampleN and helpN)? also can not so...

 $(document).on('click', 'input[type=text][id=valor_unitario1]', , 'input[type=text][id=quantidade1]', function() {
     this.select();

Right? In this case it would be right...

$(function() {
   $(document).on('click', 'input[type=text][id=valor_unitario1]', function() {
     this.select();
   });
   $(document).on('click', 'input[type=text][id=qnt1]', function() {
     this.select();
   });
 });

Any suggestions?

2 answers

2


You can do it the way you put it, passing the desired elements as parameter, only you must put them in the same parameter separated by a comma, staying as follows:

$(document).on('click', 'input[type=text][id=valor_unitario1], input[type=text][id=quantidade1]', function() {
     this.select();
}

But it’s not a good way to do it. The best way is to put a class in each element, and in the 'click' event you assign it only once, for example:

$(document).on('click', '.copiaTexto', function() {
   this.select();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<textarea class="copiaTexto" rows="5" cols="51">
Texto para ser copiado
</textarea>

<textarea class="copiaTexto" rows="5" cols="51">
Texto para ser copiado 2
</textarea>

This way, every class that has "copy" will receive this event, including those that you add dynamically, if applicable.

1

Can use [id^=valor_unitario] to select all elements where id starts with "unit value".

You can also separate your query with a comma to select all the desired elements

$(document).on('click', '[id^=valor_unitario], [id^=qnt]', function() {
  this.select();
});

But it would be much more performative and easier to maintain if you simply assigned a common class to these elements, and then query by class, rather than using a substring of id.

Browser other questions tagged

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