2

I just recently started becoming familiar with JSON and I'm trying to figure out if I can use an IF statement inside of the JSON object. I hope I am referring that correctly.

So, in my code, I am displaying a SELECT and it's OPTION values with JSON, and the issue I am having is IF a value is NULL, display the text NONE.

This is what I have so far:

 function renderIPIEditView ($td)
 {
   var value = $td.text();
   $td.html(''); // clears the current contents of the cell
   var $select = $('<select class="form-control"></select>');
   $td.append($select);

   $.getJSON( 'api/inlands.php', function( data )
   {
     $.each(data, function(index, item)
     {  // here is where I think the IF statement should go
       $('<option>').
         attr('value', item.POINT_CODE).
         text(item.FULL_NAME+', ' +item.US_STATE).
         appendTo($select);
     });

     $select.val(value);
   });
 }

So with the code above, I can display the necessary options value and text. However, inside the table, there is one record that has a POINT_CODE of NONE, and will list the text FULL_NAME and US_STATE as NULL, NULL on the screen.

I think I need an IF statement right where I listed the comment in the code above, but I am not sure if I can even use an IF statement, let alone how to use it in this case.

1
  • here is a link that shows different datatypes of JSON json.com/#data-types Commented Dec 29, 2014 at 16:31

1 Answer 1

4

Nothing JSON-specific about it - it's a straightforward if based on an object's property:

$.each(data, function(index, item)
{ 
  if (item.POINT_CODE != 'NONE')
  {
    $('<option>').
      attr('value', item.POINT_CODE).
      text(item.FULL_NAME + ', ' + item.US_STATE).
      appendTo($select);
  }
});
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, good sir. This worked. I added an ELSE with the text displayed as (item.POINT_CODE) and now I'm getting the results I need. Thank you, thank you.

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.