Search code examples
javascriptjquerybootbox

Open Bootbox alert - Loop through array of strings and display check box list


I am opening a bootbox alert which contains a checkbox list which looks like:

bootbox.prompt({
            title: "This is a prompt with a set of radio inputs!",
            message: '<p>Please select an option below:</p>',
            inputType: 'radio',
            inputOptions: [
              {
                text: 'Choice One',
                value: '1',
              },
              {
                text: 'Choice Two',
                value: '2',
              },
              {
                text: 'Choice Three',
                value: '3',
              }
            ],
            callback: function (result) {
              console.log(result);
            }
          });

This open a prompt with a checkbox list with 3 options

How do i instead of hard coding set options i want to loop through an array of strings, and set the input options. I have tried adding a for loop inside the input options but this errors as can only include the tags inside.

Here is what i have tried:

var data = response.Data;
     bootbox.prompt({
                title: "This is a prompt with a set of radio inputs!",
                message: '<p>Please select an option below:</p>',
                inputType: 'radio',
                inputOptions:

                  for(var i = 0; i<data.length; i++) {
                [{
                  text: data[i],
                  value: data[i]
                }]
                }

                callback: function (result) {
                  console.log(result);
                }
              });

Solution

  • You need to add an array of objects, like this:

        var myCheckboxesArray = [];
        var data = [1,2,3,4,5,6];
        for(var i = 0; i<data.length; i++) {
          myCheckboxesArray.push({text: 'Choice '+data[i],value: data[i]})
        }
        bootbox.prompt({
          title: "This is a prompt with a set of checkbox inputs!",
          value: ['1', '3'],
          inputType: 'checkbox',
          inputOptions: myCheckboxesArray,
          callback: function (result) {
            console.log(result);
          }
        });