LA_
LA_

Reputation: 20429

Dynamic DOM elements creation

I should add rows to the table with jQuery:

    <table class="table">
      <tbody id="dh-values">
      </tbody>
    </table>

I've written the following code:

  function displayHash(fieldName) {
    $('#dh-values').append('<tr></tr>').append('<td id="dh-'+fieldName+'">'+$('#'+fieldName).val()+'</td>').append('<td id="dh-'+fieldName+'-h">'+hex_sha1($('#'+fieldName).val())+'</td>');
  };

But it looks awful. Is there any way to simplify that?

Upvotes: 1

Views: 448

Answers (3)

Sanjeev Kumar Dangi
Sanjeev Kumar Dangi

Reputation: 7325

You should use client side templating engine to separate html structure and business logic for manipulating the data to be binded with template in javascript.

Upvotes: 0

mplungjan
mplungjan

Reputation: 178393

Combined answer of Esalija, amnotiam et al

DEMO

function displayHash(fieldID) {
    var val = $('#'+fieldID).val();
    var valSha = hex_sha1(val);
    $("<tr>").appendTo("#dh-values")
       .append('<td id="dh-'+fieldID+'">'+val+'</td>')
       .append('<td id="dh-'+fieldID+'-h">'+valSha+'</td>');
};

Upvotes: 0

Roko C. Buljan
Roko C. Buljan

Reputation: 206595

http://jsbin.com/exopoc/edit#javascript,html,live

function displayHash(fieldName) {

  var cont = '<tr><td id="dh-'+ fieldName +'">'+ fieldName +'</td> <td id="dh-'+ fieldName +'-h">'+ fieldName +'</td></tr>';
  $(cont).appendTo('#dh-values');

}



displayHash('12345678');

Upvotes: 1

Related Questions