2

I have this code

var users = result.users; // array

$("#dialog:ui-dialog").dialog("destroy");

$("#dialog-confirm").dialog({
    resizable: false,
    height: 140,
    modal: true,
    open: function() {
    $(this).children('div.dialog-text').replaceWith("<b>New text goes here</b>");
    },

    buttons: {
    "Okay": function() {
        $(this).dialog("close");
    },
    Cancel: function() {
        is_okay = 0;
        $(this).dialog("close");
    }
    }
});

where the array contain data in the form of

{"ss":"Sandra Schlichting","fn":"Full name"}

What I am trying to accomplish is to get the content of the arrays in the form of (white space inserted for readability)

<table>
  <tr>  <td>Initials</td>  <td>Full Name         </td>  </tr>
  <tr>  <td>ss      </td>  <td>Sandra Schlichting</td>  </tr>
  <tr>  <td>fn      </td>  <td>Full name         </td>  </tr>
</table>

and have that replaced with <b>New text goes here</b> in

$(this).children('div.dialog-text').replaceWith("<b>New text goes here</b>");

From what I can tell $.each() should be used for this.

But still I can't quite figure out how to get started.

Can anyone help me out?

2 Answers 2

3

You can use a JS for-in to loop through it.

<table id='nameTable'>
  <tr>  <td>Initials</td>  <td>Full Name         </td>  </tr>
</table>

var names = {
    "ss": "Sandra Schlichting",
    "fn": "Full name"
};
var $table = $('#nameTable');
var row   = '';
for (name in names) {
    row += '<tr><td>' + name + '</td><td>' + names[name] + '</td></tr>';
}
$table.append(row)

Here's a fiddle : http://jsfiddle.net/exP2b/4/

Sign up to request clarification or add additional context in comments.

2 Comments

Nice, though for large amounts of data I wouldn't recommend doing .append within a loop. I'd build up a string and append outside.
@Gary yup definitely. Building up the elements and inserting in one go is the recommended way. Updated the answer, thanks.
2
function makeTable(users) {
    var result = '<table><tr><td>Initials</td><td>Full Name</td></tr>\n';
    $.each(users, function(index, value) {
        result += '<tr><td>' + index + '</td><td>' + value + '</td></tr>\n';
    });
    result += '</table>';
    return (result);
}

alert(makeTable({"ss":"Sandra Schlichting","fn":"Full name"}));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.