0

Ok this must have a simple solution but I'm breaking my head over this one...

I have a js code which picks up ID numbers from my HTML by class. It stores all in an array. I checked that the array is not undefined and is not empty. Sofar so good.

Now I need to get this array of ID's to display into an HTML element. The full array should just come out as a comma separated string.

The piece of code which is relevant:

    function makelink(){    
    var idArray = $(".result");
    document.getElementById("link").innerHTML = idArray;
    }
    //The result in HTML = [object Object]

When I do the following it works exactly as I want (except that I can't hardcode the array into the code like this of course)

    function makelink(){  
    var idArray = ["123", "124", "125", "126"];
    document.getElementById("link").innerHTML = idArray;
    }
    //The result in HTML = [123,124,125,126]

I read at least 4 other similar questions on Stackoverflow such as What does [object Object] mean? and Convert javascript array to string and based on that I tried:

    document.getElementById("link").innerHTML = idArray.join();

and also:

    var idArray = $(".result");
    idArray.toString();

but I could not figure out how to make it work for my code. I don't need to alert or console.log. I need my result to be output in the HTML. Please help.

J.K.
  • 167
  • 1
  • 10

3 Answers3

0

You are not displaying the array, but the jQuery object of the DOM element. You might need the map function. But this function is not enough by itself, you will still need to get the value of the result object, or the html, but that part is the easiest.

function makelink(){    
    var idArray = $(".result").map(function(item) { 
        return item.val(); 
    }).get();
    document.getElementById("link").innerHTML = idArray;
}
tvili999
  • 101
  • 4
  • jQuery `map()` does not return an array, you need to chain additional methods to get results as array `(get() or toArray())` – charlietfl Aug 02 '20 at 15:18
0

You can try this:

function makelink(){  
  var idArray = [];
  $(".result").each(
    function(){
      idArray.push($(this).text())
    }
  );
  document.getElementById("link").innerHTML = idArray.join(', ');
}
Will Black
  • 350
  • 2
  • 17
  • In theory this is not as efficient as using functional programming functions like map, as this will take up a 0 sized array, and the push makes the array grow and in memory this will make the array be reallocated every time it exceeds its allocated memory space. It might be optimalized by the JS engine so might not matter. And also it is a good practice to use immutable data most of the times. Anyway good simple solution, no offense. – tvili999 Aug 03 '20 at 17:16
-1

Do this ::

function makelink() {  
    var idArray = ["123", "124", "125", "126"];
    document.getElementById("link").innerHTML = JSON.stringify(idArray);
}
Rilla
  • 505
  • 4
  • 16