0

I want to display content in a div whose id is search_result, I am using following code but it is only showing the last element of the array because of innerHTML. Can anyone help me to append the data.

here is my JavaScript code

function myFunction($qw) {
    for ($i = 0; $i < data.length; $i++) {
        $dis = data[$i].charAt(0);
        var $n = ($dis.localeCompare($qw))
        if ($n == 0)
            document.getElementById("search_result").innerHTML = (data[$i] + "<br/>");
    }
    $i = 0;
}

Here is my HTML code :

<div id="search_result">
</div>
2
  • Atleast use some logics and do some efforts before posting such questions Commented Feb 26, 2015 at 14:33
  • 1
    Use += instead of =. You are replacing what is already contained in the element by setting it to a new value every iteration. Commented Feb 26, 2015 at 14:33

3 Answers 3

2

You're replacing the content of the div with every step in your for.. loop.

function myFunction($qw)
        {
    //set  a var
    var new_content;
        for($i=0;$i<data.length;$i++){
        $dis = data[$i].charAt(0);
        var $n = ($dis.localeCompare($qw))
        if($n == 0)
    //remove replacing the innerHTML here
    //instead, add content to the variable
        new_content+=data[$i] + "<br/>";
        }

    //replace content of div after the loop
    document.getElementById("search_result").innerHTML=new_content;
        $i=0;
        }
Sign up to request clarification or add additional context in comments.

Comments

2

It is not a good practice to touch DOM on every change. I'd better do this way:

function myFunction($qw) {
  var display = [];
  var $dis;
  var $n; 
  for (var $i = 0; $i < data.length; $i++) {
    $dis = data[$i].charAt(0);
    $n = ($dis.localeCompare($qw))
    if ($n == 0)
        display.push(data[$i]);
  }
  $i = 0;
  document.getElementById("search_result").innerHTML = display.join('<br />');
}

Or fancy way

function myFunction($qw) {
  var display = data.filter(function (el) {
    var $dis = el.charAt(0);
    var $n = $dis.localeCompare($qw);
    return $n === 0;
  });
  document.getElementById("search_result").innerHTML = display.join('<br />');
}

Also use var statement to initialize variables

Comments

0

Just to add to @Sachin's answer, cache the string and then add it entirely to the dom afterwards:

function myFunction($qw) {
    var str = '';
    for ($i = 0; $i < data.length; $i++) {
        $dis = data[$i].charAt(0);
        var $n = ($dis.localeCompare($qw))
        if ($n == 0)
            str += (data[$i] + "<br/>");
    }
    document.getElementById("search_result").innerHTML = str;
    $i = 0; 
}

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.