6

I have an array called desc that contains some text for each of it's values and change's length and values depending on what the user clicks on.

array:

desc[0] =  "manhole cover on foothpath on barrog gaa grounds kilbarrack road loose."
desc[1] =  "Footpath at driveway to 17 Maywood Lawn in bad state of disrepair."

I would like to display these array values in a div called #container. At the moment it just prints the last value of the array in #container rather that printing each of the the values in the list.

JavaScript:

 function incidentList(){
            for(var i=0; i<desc.length; ++i){
             $("#container").text(desc[i]);
        }
      }

Html:

<div id="container" style="width: 50%; height:97%; float:right;"></div> 

How should I go about printing the full list with each array value underneath the last using a loop?

5
  • function incidentList() { $("#container").text(desc.join("<br />")); } Commented Nov 29, 2013 at 13:04
  • 1
    @Givi this would output '<br />' as text on the contatiner. You'll need to use $.fn.html instead. Commented Nov 29, 2013 at 13:07
  • @kayen Yes, you're right! ;) Commented Nov 29, 2013 at 13:11
  • @kayen should $.fn.html be used in place of "<br />"? Commented Nov 29, 2013 at 14:15
  • 2
    @wtmcm When you do $(container).html('<br />') it outputs the '<br />' as HTML content on the container i.e. as a line break, but when you do $(container).text('<br />') it simply displays it as plain text on the page. Commented Nov 29, 2013 at 14:18

6 Answers 6

7
function incidentList(){
  var full_list = ""
  for(var i=0; i<desc.length; ++i){
      full_list = full_list + desc[i] + '<br>'
  }
  $("#container").text(full_list);     
}
Sign up to request clarification or add additional context in comments.

Comments

1

Or simply:

$('#container').text(desc.join('\r\n'));

Comments

0
function incidentList(){
   for(var i=0; i<desc.length; ++i){
       $("#container").text( $("#container").text() + desc[i] + '<br/>');
   }
}

Comments

0

You need to use the jQuery .append method rather than .text

Comments

0
 function incidentList(){
        for(var i=0; i<desc.length; ++i){
         $("#container").append(desc[i] +"<br/>");
    }
  }

this should work

Comments

0

try this

function incidentList(){
            for(var i=0; i<desc.length; ++i){
             $("#container").append(desc[i]);
        }
      }

the method .text() will replace the content of the div but .append() will append so you will have all the data displayed.

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.