0

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
artworkjpm
  • 1,255
  • 2
  • 19
  • 40
  • 3
    Add an `option` class to each of them then just gather them all up with `$('.option')`. – Andy Apr 28 '15 at 15:50
  • You can use _starts with_ selector, as indicated in this answer: http://stackoverflow.com/a/23223564/1401341 (although author recommends adding a common class, like Andy). – Fernando Apr 28 '15 at 16:00

2 Answers2

1

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

Timotheus0106
  • 1,536
  • 3
  • 18
  • 28
  • You don't need to keep an iterator variable. The first argument of the each() callback is the iteration count. See: https://api.jquery.com/each/ – Matt Apr 28 '15 at 16:00
  • I like the idea of using a class but it didn't work. The issue seems to be with the – artworkjpm Apr 29 '15 at 08:33
  • it did work. only the variable was named wrong. arraylist and arrayList. camelcase problem. see fiddle :) http://jsfiddle.net/n4y4dhbd/1/ – Timotheus0106 Apr 29 '15 at 08:59
  • 1
    The L's in arrayList were not capitalised!!! it does work, thankyou Timmi and the others – artworkjpm Apr 29 '15 at 09:20
0

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
Ted
  • 14,757
  • 2
  • 41
  • 58