Hi Everyone,

I created a script where rows gets cloned, then I created a script to check if a specific code exists in the database. This all works fine. My problem is my status message when a code exist, it shows on the first row but not the rest. I made the id of #status unique but I can't understand why it's not showing in the dynamically created row.

Can someone please tell me what I'm doing wrong, or just lead me in the right direction?

I added my code to Jsfiddle

Dani AI

Generated

A short diagnosis and a robust fix.

The immediate bug pointed out is that the cloned element was being given an id value that included a literal #, so the DOM ended up with an id like #status... and selectors failed to find it. Fixing that is necessary, but it’s better to avoid brittle id-based lookups on cloned rows entirely. Manipulate the clone itself, use classes or data-* attributes, and keep ids unique (or avoid them).

Clone-and-update pattern (work on the clone before appending):

var $last = $('.codeForm tr').last();
var $clone = $last.clone();
counter += 1;

// give the clone a stable selector (class + unique id if you need one)
$clone.find('.status').removeAttr('id').attr('id', 'status-' + counter).text('');
$clone.find('input[type="text"]').val('');
$('.codeForm').append($clone);

Use delegated event handlers and update status relative to the row that triggered the check, so responses always go to the correct row:

$(document).on('blur', '.code-input', function() {
  var $tr = $(this).closest('tr');
  var $status = $tr.find('.status');
  var code = $(this).val();

  $.get('/check', { code: code }, function(resp) {
    $status.text(resp.exists ? 'Exists' : 'Available');
  }, 'json');
});

Also keep ’s note in mind: using bracketed names like name="code[]" is fine for form arrays, but avoid [ or ] in ids unless you escape them in selectors. Quick checklist: remove any literal # when setting id, prefer class/data selectors, target the clone object (not a global selector), use delegation for events, and inspect the DOM with devtools for duplicate ids or selector errors.

Recommended Answers

All 2 Replies

Not sure about the [] character in your id and name values, is that causing them to fail to be found? I always stick with the basic rule for ids, which I think is:
[A-Za-z][-A-Za-z0-9_:.]*

On line 11 you have:

$('.codeForm tr:last div[id="status"]').attr('id', '#status' + counter + '');

which ends up generating <div id="#status">...</div>. Get rid of the hash symbol. You need the hash symbol only when using selector expressions for jquery, not for the actual ids of the elements. It should be:

$('.codeForm tr:last div[id="status"]').attr('id', 'status' + counter );
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.