skip to Main Content

As anticipated by the title I want to make the html element of sweetalert dynamic.

In particular, I have an array with elements inside it.
My goal is to create as many checkboxes as there are elements in the array.

I tried to use foreach inside the html method that sweetalert2 provides, but as you can easily see from the reproducible example below I get nothing.

const arr = ['Alex','Jasmine','Andrie','Elton','Susy'];

function test() {
Swal.fire({
    html: 
    arr.forEach(user => {
        `  
        <div>
            <input type="checkbox" id="user" name="user" value="">
            <label for="">User</label><br>
        </div>
        `
    }),
    focusConfirm: false,
  })
}

document.getElementById ("test").addEventListener ("click", test);
<script src="https://unpkg.com/[email protected]/dist/sweetalert2.all.js"></script>



  <button type="button" id="test" class="button">
    Click
  </button>

Can someone help me? Can you tell me where I am going wrong?

2

Answers


  1. Chosen as BEST ANSWER

    If anyone else is interested and wants to try a different method, you can do so with the map array method.

    const arr = ['Alex', 'Jasmine', 'Andrie', 'Elton', 'Susy'];
    
    function test() {
      Swal.fire({
        html: arr.map(user => {
          return (
            `<div>
                <input class="form-check-input" type="checkbox" value="${user}">
                <label class="form-check-label" for="flexCheckDefault">${user}</label>
            </div>`
          )
        }).join(""),
        focusConfirm: false,
      })
    }
    
    document.getElementById("test").addEventListener("click", test);
    <script src="https://unpkg.com/[email protected]/dist/sweetalert2.all.js"></script>
    
    <button type="button" id="test" class="button">Click</button>

    Note that I used the join("") method because when I printed the various users the comma (the separator of the array elements) was also printed.


  2. You should accumulate all those value you return from forEach into a long string of HTML. It’s easier to do with reduce.

    const arr = ['Alex', 'Jasmine', 'Andrie', 'Elton', 'Susy'];
    
    function test() {
      Swal.fire({
        html: arr.reduce((agg, user, index) => {
          agg += `  
            <div>
                <input type="checkbox" id="user${index}" name="user" value="">
                <label for="user${index}">${user}</label><br>
            </div>
            `
          return agg;
        }, ''),
        focusConfirm: false,
      })
    }
    
    document.getElementById("test").addEventListener("click", test);
    <script src="https://unpkg.com/[email protected]/dist/sweetalert2.all.js"></script>
    
    
    <button type="button" id="test" class="button">Click</button>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search