0

I have an <input> field that, when you start to type in something, a live ajax result is returned with the result, kind of like "Auto suggest" except that, instead of in the <input>, the results are displayed in a <div>. The problem is that it does not return the results in an expected fashion. It only seems to return one result, the "last" one if you will. Below is code I found on the net and adapted to suit my needs.

so I have the following HTML

<input class="getter" id="search" name="search" type="text" value="" /> 
<div class="data" id="results">
    Gonzo
</div>

and the following JavaScript

<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
<script>
    $(document).ready(function() {

        $('#search').keyup(function() {
            var q = $(this).val();
            var regex = new RegExp(q, "i");
            var count = 1;
            var output = '';
            $.getJSON('http://www.fizzydrink.eu/alice.json', function(data) {
                $.each(data, function(key, val) {
                    if ((val.name.search(regex) != -1)) {
                        output = val.name + val.color;
                        if(count%2 == 0) {
                            output = '<p></p>';
                        }
                        count++;
                    }
                });
                $('#results').html(output);
            });
        });

    });
</script>

You can find a demo on jsFiddle. Also, attached below is the raw JSON file:

[
    {"name":"alice","color":"red","at":"@alice"},
    {"name":"albert","color":"cyan","at":"@albert"},
    {"name":"bob","color":"green","at":"@bob"},
    {"name":"bertrand","color":"purple","at":"@bertrand"},
    {"name":"peter","color":"blue","at":"@peter"}
]
2
  • try replacing both output = with output += Commented Nov 26, 2014 at 18:30
  • Wow, it works! Thanks. Please create answer so that I can accept. Also, can you please explain why this is? I'm not sure I get it. Commented Nov 26, 2014 at 18:35

1 Answer 1

1

You are creating an output variable:

output = '';

But instead of concatenating, you are constantly replacing it with a new string:

//Instance 1
output = val.name + val.color;

//Instance 2
output = '<p></p>';

Instead you should be adding to it:

//Explicitly
output = output + val.name + val.color;

//Shorthand (does exactly the same as the line above)
output += val.name + val.color;
Sign up to request clarification or add additional context in comments.

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.