Set new item id in jquery

I have code to change the new id for an element with jquery.

$('.trclick').click(function(){
  var id = $(this).attr('id');
  var idright = split_right(id,'__');
  var val = $('#ims_master_test_day1__'+idright).val();

  $('#ims_master_test_day').attr( 'id', 'ims_master_test_day__' + idright );
});

It works, but only one is active. Please help me. Thank!

+3
source share
2 answers

I'm going to suggest that you mean "it only works the first time it is called" when you say "It works, but it is only active one." The reason for this is this line of code:

$('#ims_master_test_day').attr( 'id', 'ims_master_test_day__' + idright );

You get the element by its identifier, but then change it. This does not work a second time because the item no longer has this identifier. You can fix this by doing something like this:

var test_day = $('#ims_master_test_day')

$('.trclick').click(function(){
  var id = $(this).attr('id');
  var idright = split_right(id,'__');
  var val = $('#ims_master_test_day1__'+idright).val();

  test_day.attr( 'id', 'ims_master_test_day__' + idright );
});
+6
source

// this won't work the second time because the id is different now
$('#ims_master_test_day').attr( 'id', 'ims_master_test_day__' + idright );

, . , - :

// cache the current id in some variable somewhere :)
var currentId;
$('.trclick').click(function(){
  var id = $(this).attr('id');
  var idright = split_right(id,'__');
  var val = $('#ims_master_test_day1__'+idright).val();

  $('#'+currentId).attr( 'id',  'ims_master_test_day__' + idright);

  // set the current id
  currentId = 'ims_master_test_day__' + idright;
});
0

All Articles