w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Javascript function is overwritting all of my results when returning them to a class

This block of code is just stuffing item after item into the same set of HTML elements with this line $('.item-name').html(items);:

    for ( var i = 0; i < 6; i++ ) {
        var items = data.result.items[arr[i]].item.toString();
        $('.item-name').html(items);
    }

So, you will only end up with arr[5] in all $('.item-name') elements.

It is unclear exactly what you want the result to be. Please describe further what you are trying to accomplish.


If you're trying to select six random result out of everything that is returned, and put them into each of six items with class="item-name" that already exist, then you would do that like this:

function getitems() {
    var arr = [];
    for (var i = 0; i < 6; i++) {
        arr.push(Math.floor((Math.random()*72)+1));
    }
    $.getJSON('items.json',function(data) {
        var items = $('.item-name');
        for ( var i = 0; i < 6; i++ ) {
            var result = data.result.items[arr[i]].item.toString();
            items.eq(i).html(result);
        }
    }).error(function(){
    });
}

Note, this won't guarantee that each of the six random results is different. You might have the same result repeated. I'm also not sure why you are adding 1 to the random result because I would assume that data.result.items is a zero-based array so you would want to include the 0 index too.


If you wanted to also make sure each random result was unique, you could do that like this:

function getitems() {
    var arr = [], used = {}, val;
    for (var i = 0; i < 6; i++) {
        do {
            val = Math.floor((Math.random()*72)+1);
        } while (!(val in used));
        used[val] = true;
        arr.push(val);
    }
    $.getJSON('items.json',function(data) {
        var items = $('.item-name');
        for ( var i = 0; i < 6; i++ ) {
            var result = data.result.items[arr[i]].item.toString();
            items.eq(i).html(result);
        }
    }).error(function(){
    });
}




© Copyright 2018 w3hello.com Publishing Limited. All rights reserved.