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 sweetalert 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/sweetalert2@7.18.0/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?
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/sweetalert2@7.18.0/dist/sweetalert2.all.js"></script>
<button type="button" id="test" class="button">Click</button>