sunny_side_of_life sunny_side_of_life - 7 months ago 11
Javascript Question

How to achieve this without refreshing the page using jQuery?

I have a web page that populates a table via jQuery.

Since I only want to change classes of a particular

<td>
element I used
replaceWith
. This worked well on the first search, but I realized that I could not asynchronously perform another search without first refreshing my page. I then tried
html
instead of
replaceWith
. This worked well, but crammed all the new
<td>
into one
<td>
that has the specified id.

How can I achieve this without refreshing the page so that I can get the
<td>
elements well distributed?

Before updating:

<table>
<tr>
<td>first row</td>
<td>measure1</td>
<td>measure2</td>
<td>measure3</td>
<td>measure4</td>
<td> </td>
</tr>
<tr>
<td>First row</td>
<td id="no_rec" colspan="4"> No record to display!</td>
<td>More+</td>
</tr>
</table>


After updating I expect to have a table of the format:

<table>
<tr>
<td>first row</td>
<td>measure1</td>
<td>measure2</td>
<td>measure3</td>
<td>measure4</td>
<td> </td>
</tr>
<tr>
<td>First row</td>
<td class="new"></td>
<td class="new"></td>
<td class="new"></td>
<td class="new"></td>
<td>More+</td>
</tr>
</table>


My JavaScript:

$('#mybutton').click(function()
{
$.post
(
'search.php',
{
regNo: $("#regNo").val(),
datepicker: $(".datepicker").text()
},
function(data)
{
$.each(data, function(i)
{
var tm = data.time;

add_html='';

for (i=0; i<4; i++)
(i === 0 || i === 2)
? add_html += '<td class="new"></td>'
: add_html += '<td></td>';

$('#no_rec').replaceWith(add_html);
});
},
'json'
);
});


My JsFiddle Attempts

Answer

What I did was add id=results to the tr so that I could find and store all td tags and then manipulate them accordingly.

See working jsFiddle demo

All notes are left in the comments of the jQuery, but one that I should mention here is that I added a simulateData() function that basically allows you to click the Update button as many times as you want to see how the code will handle different data that's returned.


HTML


<table border="1">
    <tr>
        <td>first row/measures</td>
        <td>measure1</td>
        <td>measure2</td>
        <td>measure3</td>
        <td>measure4</td>
        <td>measure5</td>
    </tr>
    <tr id="results">
        <td>First row</td>
        <td colspan="4">No record to display!</td>
        <td>More+</td>
    </tr>
</table>
<button>Update</button>


jQuery


var noRecord = "<td colspan=\"4\">No record to display!</td>",
    currentTime = 0;

$( "button" ).click( function ()
{    
    var $results = $( "#results" ),              // Get the TR.
        $tds = $( "#results" ).find( "td" ),     // Get the TDs within the TR.
        data = simulateData();                   // Simulate data.

    // Check to see if data was returned.

    if ( data === undefined )
    {
        // Data was not returned.

        if ( $results.html().indexOf( noRecord ) === -1 )
        {
            // Results TR has previous values that need to be removed.

            for ( i = 1; i < 5; i++ )
                $( $tds[i] ).remove();

            // Add back the [No record to display!] TD.

            $( noRecord ).insertAfter( $tds[0] );
        }
    }
    else
    {
        // Data was returned.

        $.each( data, function ( i ) 
        {
            // Store the current data.

            var tm = parseInt( data.time );

            // Check to see if the Results TR has previous values or not.

            if ( $results.html().indexOf( noRecord ) > -1 )
            {
                // Results TR does not have previous values.

                var html = "";

                // Generate new TDs.

                for ( i = 1; i < 5; i++ )
                    html += "<td class=\"new\">" + tm + "</td>";

                // Remove [No record to display!] TD and replace with new TDs.

                $( $tds[1] ).replaceWith( html );
            }
            else
            {
                // Results TR has previous values so we need to loop 
                // through each existing TD replacing its class and value.

                for ( i = 1; i < 5; i++ )
                {
                    if ( i != tm )
                    {
                        // Change class to "new" and add stored data value.

                        $( $tds[i] )
                            .removeClass( "rr" )
                            .addClass( "new" )
                            .text( tm );
                    }
                    else
                    {
                        // Change class to "rr" and add "ee" value.

                        $( $tds[i] )
                            .removeClass( "new" )
                            .addClass( "rr" )
                            .text( "ee" );
                    }
                }
            }
        });
    }
});


// This simulates the async calls to search.php to generate 
// different times on each click of the Update button.

function simulateData()
{
    // Increment our simulated time.

    currentTime++;

    if ( currentTime > 4 ) 
    { 
        // Start over by resetting our incrementer.

        currentTime = 0; 

        // Simulate a call that doesn't return data.

        return undefined;
    }
    else 
    {
        return { "time": currentTime }
    }
}