user1955162 user1955162 - 5 months ago 10
jQuery Question

Javascript / JQuery Append the return of a function in a concatenated string

I have a function that returns a string:

function buildCell(){
var returnString = '';
returnString += '<td>';
returnString += 'Cell Contents';
returnString += '</td>';
return(returnString);
}


I have another function that should invoke the first string and return its value inline:

function buildTable(){
$('body').html(
'<table>'
+'<tr>'
+ buildCell()
+'</tr>'
)
}


My table doesn't have the cell, the cell comes back undefined. How do i properly concatenate the return of the first function in the second?

Edit: I removed the semicolon and still receive "undefined". When I place an alert in the first function I see the correct value in the alert, but it is still undefined in the second function.

Answer

You have incorrectly placed semi-colons inside buildTable function > buildCell();

Change your function from this:

function buildTable(){
    $('body').html(
         '<table>'
         +'<tr>'
         + buildCell(); // <---
         +'</tr>'
    )
}

To this:

function buildTable() {
    return $('body').html('<table>' + '<tr>' + buildCell() + '</tr>');
}

https://jsfiddle.net/k0ageq81/

function buildCell() {
  var returnString = '';
  returnString += '<td>';
  returnString += 'Cell Contents';
  returnString += '</td>';
  return returnString;
}

function buildTable() {
  return $('body').html('<table>' + '<tr>' + buildCell() + '</tr>');
}

buildTable();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

Comments