1

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?

6
  • 2
    You are actually appending the tds to tbody Commented Jun 17, 2012 at 16:14
  • You only need one .append() call. You can build the entire string of <tr><td></td><td></td></tr> and append it once. It isn't necessarily prettier though. Commented Jun 17, 2012 at 16:16
  • 1
    It looks awful because you're "chaining". Separate each method call onto a new line. The snippet could also use some variables. Commented Jun 17, 2012 at 16:17
  • @Esailija, I've checked the code generated, it is correct - <tbody><tr><td></td><td></td></tr></tbody> Commented Jun 17, 2012 at 16:24
  • 1
    @LA_ not in here jsfiddle.net/EsEZD Commented Jun 17, 2012 at 16:35

3 Answers 3

1

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');
Sign up to request clarification or add additional context in comments.

Comments

0

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>');
};

6 Comments

still appending to the tbody though
.append returns the jQuery object it operates on
Almost. If this function is called more than once, you'll be selecting all tr elements every time. You only want the new one.
so now it appends to all tr?
You could do with $("<tr>").appendTo("#dh-values").append("td stuff here")
|
0

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.

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.