0

I have these code:

function ambil_coa(hal_aktif,scrolltop){
  if($('table#coa-list').length > 0){
    // alert('ada tablenya');
    $.ajax('http://'+host+path+'/ambil',{
      dataType:'json',
      type: 'POST',
      success: function(data){
        $('table#coa-list tbody tr').remove();
        $.each(data.record , function(index, element){
           $('table#coa-list').find('tbody').append(
                '<tr align="center">'+
                ' <td class="text-nowrap">'+element.no_urut+'</td>'+
                ' <td class="text-nowrap">'+element.customer_ID+'</td>'+
                '</tr>'               
            )
        });
      }

    });
  }
}

I want to add some conditional statement below.

If element.customer_ID return 0, echo "-";
else if the value not 0 echo "Customer Name"

How to write the conditional script to the append section?

3
  • You can user html(' your html code ') or append() Commented Mar 12, 2017 at 14:36
  • var element = ""; $.each(data.record , function(index, element){ element += '<tr align="center">'+ ' <td class="text-nowrap">'+element.no_urut+'</td>'+ ' <td class="text-nowrap">'+element.customer_ID+'</td>'+ '</tr>'; ) }); $('table#coa-list').html(element); Commented Mar 12, 2017 at 14:38
  • It is not clear what you are actually trying to ask here. Can yu be a bit more specific Commented Mar 12, 2017 at 14:39

1 Answer 1

2

The simplest way will be using ternary operator:

$('table#coa-list').find('tbody').append(
    '<tr align="center">'+
    ' <td class="text-nowrap">'+element.no_urut+'</td>'+
    ' <td class="text-nowrap">'+(element.customer_ID == 0? '-' : 'Customer Name' )+'</td>'+
    '</tr>'               
)

If you want to use another element property, then:

$('table#coa-list').find('tbody').append(
    '<tr align="center">'+
    ' <td class="text-nowrap">'+element.no_urut+'</td>'+
    ' <td class="text-nowrap">'+(element.customer_ID == 0? '-' : element.customer_Name )+'</td>'+
    '</tr>'               
)
Sign up to request clarification or add additional context in comments.

4 Comments

It's return Customer Name to each row, even if element.customer_ID not zero. Any idea?
If Customer name is shown then all customer_ID are not zeroes, you can check them with console.log for example.
my bad, yes you right. It's fully work. How to replace the Customer name with value of element.customer_address?
See second example please.

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.