简体   繁体   中英

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM