3

I am trying to append some data in html table using jquery that is working fine but when the data is null or empty i have to append another div to that html table.

Am trying like this

$("#table").append(data.d[i].one!=""?
    "<td id='divs'>
       <input id="+ data.d[i].one +" type=" + "checkbox" + " class=" + "cbCheck" + ">
       <label  for="+ data.d[i].one +"></label>
    </td>":"<div></div>");

but it is not working please help me how to fix this...

Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101
Raviteja
  • 257
  • 3
  • 18

3 Answers3

1

Never understand why somebody use this

$("#table").append(data.d[i].one!=""?
    "<td id='divs'>
       <input id="+ data.d[i].one +" type=" + "checkbox" + " class=" + "cbCheck" + ">
       <label  for="+ data.d[i].one +"></label>
    </td>":"<div></div>");

Instead of this:

    //class declaration
    function YourTableCell(name, value) {
       this.input = document.createElement('input');
       this.input.value = value;
       this.input.name = name;
       this.label = document.createElement('label');
       this.label.text = 'My Label';
       this.container = document.createElement('td');
       this.container.appendChild(this.input);
       this.container.appendChild(this.label);
    }


    //application buisness logic
    if(data.d[i].one != ''){
      var cell = new YourTableCell(data.d[i].name, data.d[i].value);
      $("#table").append(cell.container);
    } else {
      $("#table").append(document.createElement('div'));
    }

Using this approach you can incapsulate table cell building inside of your class and make your code much more readable and reusable. Also, as I see now, you are trying to append td inside of something with id #table, and look like it is incorrect, because you should append td inside of tr.

Also, using this you can get references to all objects such as inputs and avoid of $('input, select, textarea') selectors.

degr
  • 1,559
  • 1
  • 19
  • 37
0

You could use :

if( data.d ){
    //Your code
}

That will check if data.d is NULL or empty string "".

If you want to check in every iteration use the index i :

if( data.d[i] ){
    //Your code
}

Hope this helps.

Take a look to https://stackoverflow.com/a/5515349/4281779.

Community
  • 1
  • 1
Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101
0

You could use something like this,

var html = '<div></div>';

if(data.d[i].one) {
    html = '<td id="divs"><input id="' + data.d[i].one + '" type="checkbox" class="cbCheck"><label  for="' + data.d[i].one + '"></label></td>';
}

("#table").append(html);
Thaadikkaaran
  • 5,088
  • 7
  • 37
  • 59