Indira
Indira

Reputation: 49

HTML change content using javascript,ajax,jquery

I have a table in my phtml file.

<table width="700" class="detais" cellpadding="10px;">
<tr><td></td><td></td></table>

I also have a drop down, on change of this drop down it will call a javascript which is

function filterbyaptno(){
     var idno = document.getElementById("aplist").value;
      $.ajax({
        url: 'address',
        type: 'POST',                    
        data:"idno="+idno,
         success:function(result) { 
            var numRecords = parseInt(result.rows.length);
            if(numRecords>0)
            {
              for(var i = 0; i<numRecords;i++)
               {
                 var html ='<div class="support"><table><tr>      <td>'+result.row[i].firstname+'</td>                        
               +'<td>'+result.rows[i].advice+'</td>'         
               +'<td>'+result.rows[i].customdata+'</td><tr></table></div>' 
               }
           $('.detais').replaceWith(html);//am trying to change the table content
             }
         });
   } 

But what happens if the result has more records it just give me only the last record. And also if i change the drop down again it never works. Can anyone help me how to do this? Is there any way in javascript to modify the content of the table based on the response of controller;

Upvotes: 1

Views: 288

Answers (2)

Anthony Grist
Anthony Grist

Reputation: 38345

You're re-assigning the value of the html variable in each iteration of the for loop which means that in each iteration you're replacing the previous value with the new value, rather than concatenating the previous value and new value.

Modify your code to look like this:

if (numRecords > 0) {
    var html = '';
    for (var i = 0; i < numRecords; i++) {
        html += '<div class="support"><table><tr>      <td>' + result.row[i].firstname + '</td>' + ' < td > ' + result.rows[i].advice + ' < /td>' + '<td>' + result.rows[i].customdata + '</td > < tr > < /table></div > '
    }
    $('.detais ').replaceWith(html); //am trying to change the table content
}

Upvotes: 0

Alex K.
Alex K.

Reputation: 175766

As you loop the results you:

var html = ..

which replaces whats already in the html variable.

Declare var html outside the for loop & always append (html += ...) within the loop.

You probably also want to setup the container <div class="support"><table> outside the loop also, only adding rows within.

Upvotes: 2

Related Questions