Search code examples
javascriptjqueryarraysiterated-function

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

Solution

  • 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