redditor
redditor

Reputation: 4266

Select multiple elements with similar ID

I would like to minimise this code:

$('#thistext0').keyup(function(e){
      var keyed = $(this).val();
      $("#target").html(keyed);
 });
$('#thistext1').keyup(function(e){
      var keyed = $(this).val();
      $("#target").html(keyed);
 });
$('#thistext2').keyup(function(e){
      var keyed = $(this).val();
      $("#target").html(keyed);
 });
$('#thistext3').keyup(function(e){
      var keyed = $(this).val();
      $("#target").html(keyed);
 });

Is something like this possible in JS?

$('#thistext[i]').keyup(function(e){
      var keyed = $(this).val();
      $("#target").html(keyed);
 });

If so, how?

EDIT: I cannot use classes because the way I am looping through records with PHP, I have to use IDs

Upvotes: 0

Views: 544

Answers (3)

j08691
j08691

Reputation: 207861

Use jQuery's starts with attribute selector:

$('[id^="thistext"]').keyup(function(e){
      var keyed = $(this).val();
      $("#target").html(keyed);
});

Upvotes: 2

PSL
PSL

Reputation: 123739

A startswith selector is possible, or use a common classname.

$("[id^='thistext']").keyup(function(e){
      var keyed = $(this).val();
      $("#target").html(keyed);
 });

While using startwith selector provide a parent container as context for safety i.e $("[id^='thistext']", 'container')

Also do remember that this will be slower than native id or class selector as this is an attribute selector.

attribute-starts-with-selector

So providing a common classname to all of those textboxes and selecting then using the classSelector would be ideal i believe.

Upvotes: 6

bfavaretto
bfavaretto

Reputation: 71908

No, but this is possible:

$('#thistext0, #thistext1, #thistext2, #thistext3').keyup(function(e){
      var keyed = $(this).val();
      $("#target").html(keyed);
});

Of course, the selector string can be created in a loop. Or just add a class to your input fields, and select by class.

Upvotes: 3

Related Questions