Reputation: 5345
I am trying to use sweetalert and want to insert HTML below the title.
Find below my minimum viable example:
let shareIt = `<div><input id="myInput" class="swal-content__input" placeholder="" value="This is some text"/></div>`
swal({
title: "Good job!",
content: `${shareIt}`,
icon: "success"
})
<script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
Any suggestions how to display my HTML from my shareIt
variable?
Upvotes: 0
Views: 1554
Reputation: 3242
You can use SweetAlert2 for this, like below:
It is similer to Sweet Alert JavaScript.
swal({
title: "<i>Title</i>",
html: "Testno sporocilo za objekt: <b>test</b>",
confirmButtonText: "V <u>redu</u>",
});
<script src="https://cdn.jsdelivr.net/npm/sweetalert2"></script>
If you want to USE Text box OR AJAX, You can use below script:
swal({
title: 'Submit your Github username',
input: 'text',
inputAttributes: {
autocapitalize: 'off'
},
showCancelButton: true,
confirmButtonText: 'Look up',
showLoaderOnConfirm: true,
preConfirm: (login) => {
return fetch(`//api.github.com/users/${login}`)
.then(response => {
if (!response.ok) {
throw new Error(response.statusText)
}
return response.json()
})
.catch(error => {
swal.showValidationError(
`Request failed: ${error}`
)
})
},
allowOutsideClick: () => !swal.isLoading()
}).then((result) => {
if (result.value) {
swal({
title: `${result.value.login}'s avatar`,
imageUrl: result.value.avatar_url
})
}
})
<script src="https://unpkg.com/[email protected]/dist/sweetalert2.all.js"></script>
Upvotes: 1
Reputation: 9388
For custom content
, you need to pass a DOM node
.
From: https://sweetalert.js.org/guides/#using-dom-nodes-as-content
This might look very complex at first, but it's actually pretty simple. All we're doing is creating an input tag as a React component. We then extract its DOM node and pass it into under the swal function's content option to render it as an unstyled element.
(Emphasis mine)
Since we need to turn your template literal into a DOM node, we could use document.createElement('template')
and then assign innerHTML
to your literal. This will allow us to then call document.importNode
(which returns a document-fragment), which we can query and pass the element to swal.
Note: How you choose to create the DOM node(s) from your template literal is up to you (for instance, you might be a fan of just calling document.createDocumentFragment
straight up or creating a div
element and assigning innerHTML that way...)
Snippet example:
let template = document.createElement('template');
template.innerHTML = `<div><input id="myInput" class="swal-content__input" placeholder="" value="This is some text"/></div>`;
let shareIt = document.importNode(template.content, true).querySelector('div');
swal({
title: "Good job!",
content: shareIt,
icon: "success"
})
<script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
Upvotes: 1