Wern Ancheta
Wern Ancheta

Reputation: 23317

Generating 2 dom elements in javascript

How do I debug problems like this. I have this code:

var index = 0;
$('#gen_field').click(function() {

    var next_row = $('<tr>').attr({
        'id': 'tbl_row' + index
    }).appendTo('#tbody_coll');

    var td1 = $('<td>').attr({
        'id': 'td_collector' + index
    }).appendTo(next_row);
    var td2 = $('<td>').attr({
        'id': 'td_rem' + index
    }).appendTo(next_row);

    var collector = $('<input>').attr({
        'type': 'text',
        'name': 'collector[]'
    }).appendTo(td1).css('width', '200px');

    var rem_btn = $("<input>").attr({
        'type': 'button',
        'id': index,
        'name': 'rem',
        'class': 'rem',
        'value': 'del'
    }).appendTo(td2).addClass('span-2');

    console.log(index);
    index++;
});

This is supposed to generate only 1 field at a time. But its generating 2 of the same fields at once. Console.log is also showing 2 zeroes, then 2 ones when I click on the button that generates the fields. But I couldn't get any further into debugging this problem using firebug. Can you tell me what's wrong with my code?

Upvotes: 0

Views: 57

Answers (1)

Karl Knechtel
Karl Knechtel

Reputation: 61615

If this code got executed more than once, then two identical click handlers will get attached, and each will run when the #gen_field is clicked.

BTW, if you're going to pass an HTML fragment to jQuery anyway to create a tag, why not specify the attributes at the same time in HTML instead of using .attr()?

Upvotes: 1

Related Questions