bert
bert

Reputation: 4059

Output random item from javascript array

So I have this code:

$('.submit_button').click(function() {
        var optionsArray = $(".inputID").map(function() {
            return this.value;
        }).get().join(",");

        var randomOutput = optionsArray[Math.floor(Math.random()*optionsArray.length)];

        console.log(randomOutput);

    });

What I'm trying to do upon clicking the button (.submit_button) is for it to take the user entered data (they are inputs with the class .inputID), store them in an array (which i have done and it works) and then console.log (at least for now while I'm testing) one of the inputs at random. What it currently does is just console.logs a single character instead of a whole item from the array. What am I doing wrong?

Upvotes: 0

Views: 58

Answers (2)

surajck
surajck

Reputation: 1175

You are doing a join. So optionsArray is one single string, not an array anyomore. So optionsArray[<anything>] is basically a character.

Remove the join(",") part and it'll work.

Upvotes: 1

Oleksandr T.
Oleksandr T.

Reputation: 77522

Remove join

    var optionsArray = $(".inputID").map(function() {
        return this.value;
    }).get();

join() method joins the elements of an array into a string, and returns the string.

Upvotes: 3

Related Questions