0

Inspired by this answer here I am cloning a set of elements with jquery and renaming the id's accordingly in a .find .each loop to keep them unique.

like this:

newElement.find(':input').each(function() {
    var name = $(this).attr('name').replace('-' + 0 + '-','-' + total + '-');
    var id = 'id_' + name;
    $(this).attr({'name': name, 'id': id}).val('').removeAttr('checked');
});

So far so good, my goal is to check a checkbox in there as well that the form was originally cloned.

1) I have two ways to achieve this, I set the checkbox within the selector before renaming of the id's take place.

$newElement  ??? -->  $('#id_deals-0-is_form_cloned_by_ajax').prop('checked', true);

2) Or I wait until the id's have been renamed and have been made unique:

$('#id_deals-' + total + '-is_form_cloned_by_ajax').prop('checked', true);

The problem with the second approach is that the .find . each is an asynchronous approach and the renaming might have not taken place by the time I try to look for that checkbox's id to set it.

Hence I thought approach one is safer, but I have no idea how to check for an ID within a selector only.

May anyone point me to the right direction please?

Community
  • 1
  • 1
Houman
  • 64,245
  • 87
  • 278
  • 460

2 Answers2

0

Use .find like you have before to find the ID. Simples?

http://api.jquery.com/find/

David
  • 2,053
  • 2
  • 16
  • 26
  • you mean like this? `$newElement.find('#id_deals-0-is_form_cloned_by_ajax').prop('checked', true);` – Houman Sep 24 '12 at 09:37
0
$newElement.find(':input').each(function() {
    var name = $(this).attr('name').replace('-' + 0 + '-','-' + total + '-');
    var id = 'id_' + name;
    $(this).attr({'name': name, 'id': id}).val('').removeAttr('checked');
});

// Find an element within $newElement
$newElement.find('#id_deals-' + total + '-is_form_cloned_by_ajax').attr('checked', true);
Chris Dixon
  • 9,147
  • 5
  • 36
  • 68
  • Alright. Since find.each is actually synchronous after all, the second option is the better choice. Thanks. – Houman Sep 24 '12 at 10:12