artworkjpm
artworkjpm

Reputation: 1337

Iterate through Id's, store values, put into an array

I want to be able to iterate through a number of ids called "#option1", "#option2" etc. The problem is its for an interactive form and I don't know how many options there will be. So I need a way to iterate through the amount in the DOM when the user clicks ("#dothis").

Then I need to get the values of the those options, put into an array called arraylist.

$("#doThis").on("click", function() {
            var optionone = $("#option1").val();
            var optiontwo = $("#option2").val();
            var optionthree = $("#option3").val();
            var optionfour = $("#option4").val();
            var optionfive = $("#option5").val();
            var arrayList = [optionone, optiontwo, optionthree,
                optionfour, optionfive];
            var decide = arrayList[Math.floor(Math.random() *
                arrayList.length)];
            $("#verdict").text(decide);
        }); // end of dothis click event

Upvotes: 0

Views: 202

Answers (2)

Timotheus0106
Timotheus0106

Reputation: 1586

As Andy said, give every option the same class. In my example it's "option-item".

$("#doThis").on("click", function() {
  var arrayList = [];
  $('.option-item').each(function(i) {
    arrayList[i] = $(this).val();
  });
  var decide = arrayList[Math.floor(Math.random() *
      arrayList.length)];
  $("#verdict").text(decide);
});

Every value is now stored in the array.

see fiddle.

greetings timmi

Upvotes: 1

Ted
Ted

Reputation: 14927

With your code as is, you can use a selector that selects everything with an ID that starts with 'option', like so [id^="option"], here's how to use it:

   $("#doThis").on("click", function () {
        var arrayList = [];
        $('[id^="option"]').each(function (index, element) {
            arrayList.push($(element).val() );
        });

        var decide = arrayList[Math.floor(Math.random() *
            arrayList.length)];
        $("#verdict").text(decide);
    }); // end of dothis click event

Upvotes: 0

Related Questions