Meltdowner
Meltdowner

Reputation: 55

jQuery manipulating table rows from ajax response

I have a select dropdown and I can display/remove the condition outputs from my script except for one. What I'm having trouble is removing/deleting the rows created by the $.each. I'm still new with js and I've searched for solutions online but I still couldn't get it to work. Here's my code so far.

<table id="view_programs" class="table table-striped table-bordered">
    <thead>
        <tr>
            <th>Year</th>
            <th width="12%">Action</th>
        </tr>
    </thead>
    <tbody>
        <tr id="toBeRemoved">
            <td colspan="2">No program selected.</td>
        </tr>   
    </tbody>
</table>

script

if(selectedValue == '') {
    $("#delbutton").hide();

    $("#toBeRemoved td").remove();
    $("#toBeRemoved").append(
        $("<td colspan='2'>").html("No program selected.")
    ).appendTo('#view_programs');
}
else {
    $.ajax({
        url: '<?php echo site_url("query.php");?>',
        type: 'post',
        data: {option: selectedValue},
        dataType: 'json',
        success: function(response) {
            $("#delbutton").show().attr("href", "delete/program/"+encodeURIComponent(selectedValue));

            if(jQuery.isEmptyObject(response)) {
                $("#toBeRemoved td").remove();
                $("#toBeRemoved").append(
                    $("<td colspan='2'>").html("No records found.")
                ).appendTo('#view_programs');
            }
            else {
                var trHTML = '';
                $.each(response, function(key, value) {
                    trHTML += "<tr><td>"+value+"</td><td>"+value+"</td></tr>";
                });
                $('#view_programs').append(trHTML);
            }

            console.log(response);
        }
    });
}

Update: Achieved what I wanted thanks to Mr. Simon for shedding me some light. I doubt that my code could be better so I'm open to any suggestions.

changed this

<tbody>
    <tr id="toBeRemoved">
        <td colspan="2">No program selected.</td>
    </tr>   
</tbody>

into this

<tbody class="toBeRemoved">
    <tr>
        <td colspan="2">No program selected.</td>
    </tr>   
</tbody>

and this

$('#view_programs').append(trHTML);

into this

$('.toBeRemoved').append(trHTML);

and turned all the #toBeRemoved into .toBeRemoved

Upvotes: 0

Views: 944

Answers (1)

Simon H&#228;nisch
Simon H&#228;nisch

Reputation: 4958

you append your table rows to the end of #view_programs, which means after the </tbody> element... so they don't have a #toBeRemoved id which you want to remove i guess?

If you want to remove multiple rows, make sure to use a class (i.e. .toBeRemoved) instead of an id. Ids are unique identifiers for one element only.

Upvotes: 1

Related Questions