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
If anyone else is interested and wants to try a different method, you can do so with the map array method.
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.
You should accumulate all those value you return from
forEach
into a long string of HTML. It’s easier to do withreduce
.