79

I am using sweet-alert plugin to display an alert. With a classical config (defaults), everything goes OK. But when I want to add a HTML tag into the TEXT, it display <b>...</b> without making it bold. After searching for the answer, it looks like I don't have the right search word...

How to make sweet alert display the text also with HTML code?

var hh = "<b>test</b>";
swal({
    title: "" + txt + "", 
    text: "Testno  sporocilo za objekt " + hh + "",  
    confirmButtonText: "V redu", 
    allowOutsideClick: "true" 
});
user456584
  • 86,427
  • 15
  • 75
  • 107
Peter
  • 1,589
  • 2
  • 20
  • 27
  • 1
    It sounds like the plugin uses `text()` to insert content, therefore HTML is encoded. Unless there is an option to change this behaviour you will most likely have to find a different plugin. – Rory McCrossan Nov 10 '14 at 07:48
  • 1
    Thank you for this suggestion and help. I've researched the code of sweet-alert.js where I've found this line: $text.innerHTML = escapeHtml(params.text || '').split("\n").join("
    "); I removed changed the $text.innerHTML. Now it works: $text.innerHTML = params.text;
    – Peter Nov 10 '14 at 08:09
  • If all you are doing is changing the font you should be doing that with CSS (changing the h2 class for the title, for example). I would say it is also a mistake not to be worried about XSS attacks (see @teamjamieson). – Elin Jan 23 '15 at 10:19

12 Answers12

225

The SweetAlert repo seems to be unmaintained. There's a bunch of Pull Requests without any replies, the last merged pull request was on Nov 9, 2014.

I created SweetAlert2 with HTML support in modal and some other options for customization modal window - width, padding, Esc button behavior, etc.

Swal.fire({
  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@11"></script>
Limon Monte
  • 52,539
  • 45
  • 182
  • 213
  • Just to mention that you have some errors in code related to linking with files. Replace with that (as you probably know) – Peter Jan 26 '15 at 13:16
  • Hello @limonte , I see your answer and I have a questions, how to disable an alerts, I use sweetalert for show a "loading" message when Ajax request is start, I use jquery (.ajaxStart ) and I need hide alert when ajax request is finished. – Fernando Bernal Dec 01 '15 at 16:29
  • @FernandoArmandoBernalMarin just to let you know (if you haven't) you could use `swal.closeModal()` to close the sweetalert 2 modal. – Bagaskara Wisnu Gunawan Feb 15 '16 at 13:54
  • 1
    Is it backwards compatible with sweetalert? – pinkpanther Jun 17 '16 at 12:31
  • 2
    @pinkpanther mostly, here's the short [migration guide](https://github.com/limonte/sweetalert2/wiki/Migration-from-SweetAlert-to-SweetAlert2). – Limon Monte Jun 17 '16 at 13:41
  • @limonte can you please see this http://stackoverflow.com/questions/40386153/sweetalert-dialog-with-timer – Qammar Feroz Nov 02 '16 at 18:04
  • Congrats but... it doesn't answer op's question. – Pedro Lobito Sep 19 '17 at 00:13
  • I am using sweetalert2 and i want to use checkbox inside sweetalert2 confirm box but the problem is i want to use my checkbox and in my css i have disables checkbox.In order to use my custom checkbox how it is possible with sweetalert2.Can you please tell me i am struggling with it – I Love Stackoverflow Oct 07 '17 at 06:59
  • Pretty decent job. Thanks for doing that. The part that always baffles me is why did you limit buttons. In sweetalert you can define as many buttons as you like and assign values to them. then you can check per response and do different things. in sw2 it looks like you are limited to confirm and cancel buttons only and the only way to detect which button selected is comparing text values of the buttons which is pretty bad in practice. – serdar.sanri Jan 17 '18 at 19:48
  • 1
    See answer from @GavinR below. – Wes Dollar Feb 01 '18 at 22:11
  • @LimonMonte how do you add html with div classes in the sweet alert? – MJ DLS Dec 04 '21 at 09:43
76

A feature to allow HTML for title and text parameters has been added with a recent merge into the master branch on GitHub https://github.com/t4t5/sweetalert/commit/9c3bcc5cb75e598d6faaa37353ecd84937770f3d

Simply use JSON configuration and set 'html' to true, eg:

swal({ html:true, title:'<i>TITLE</i>', text:'<b>TEXT</b>'});

This was merged less than a week ago and is hinted at in the README.md (html is set to false in one of the examples although not explicitly described) however it is not yet documented on the marketing page http://tristanedwards.me/sweetalert

jitmo
  • 769
  • 5
  • 6
  • Ah, to use the unmerged requirejs P/R or the html-ized master. Decisions, decisions. – pztrick Jan 27 '15 at 00:33
  • 12
    As of 2017, [SweetAlert guide](https://sweetalert.js.org/guides/) says explicitly that *html is no longer used. Instead use the [content object](https://sweetalert.js.org/docs/#content)*. Thought it might help someone, since this answer has so many up-votes. – Sajib Acharya Oct 27 '17 at 07:51
  • Swal have many version but this solution work for my version (https://sweetalert.js.org/guides/#advanced-examples) thank! – Hoàng Vũ Tgtt Dec 06 '21 at 09:35
42

I was upgrading from old sweetalert and found out how to do it in the new Version (official Docs):

// this is a Node object    
var span = document.createElement("span");
span.innerHTML = "Testno  sporocilo za objekt <b>test</b>";

swal({
    title: "" + txt + "", 
    content: span,
    confirmButtonText: "V redu", 
    allowOutsideClick: "true" 
});
Vyctorya
  • 1,387
  • 1
  • 12
  • 18
14

Sweet alerts also has an 'html' option, set it to true.

var hh = "<b>test</b>";
swal({
    title: "" + txt + "", 
    html: true,
    text: "Testno  sporocilo za objekt " + hh + "",  
    confirmButtonText: "V redu", 
    allowOutsideClick: "true" 
});
Michael McHaney
  • 151
  • 1
  • 5
  • What worked for me is to assign the HTML fragment you want to display to the `html` property, instead of setting `html` to true. – Mike Finch Nov 09 '20 at 21:10
11

As of 2018, the accepted answer is out-of-date:

Sweetalert is maintained, and you can solve the original question's issue with use of the content option.

GavinR
  • 6,094
  • 7
  • 33
  • 44
  • 10
    Both this answer and the documentation on SweetAlert are about equally as helpful - which is not much in how you use the "Content Option" to render an HTML string. This answer agrees with the SweetAlert documentation here: https://sweetalert.js.org/guides/#upgrading-from-1x (3rd from bottom), but neither are showing me how to render an HTML string (not text boxes or sliders, just a string that has a `
    ` tag)
    – Tommy Feb 21 '18 at 03:00
  • 1
    I agree with @Tommy I just wanted to have es6 string template with one parameter `hello ${world}` and the examples are weird – Shnigi Oct 02 '18 at 08:59
  • 2
    The example from documentation "string" doesn't work as I expected. You just can't put it like this. content: `my es6 string template` How I solved this is: const template = (`my es6 string ${variable}`); content: { element: 'p', attributes: { innerHTML: `${template}`, }, } – Shnigi Oct 02 '18 at 09:07
10

I just struggled with this. I upgraded from sweetalert 1 -> 2. This library: https://sweetalert.js.org/guides/

The example from documentation "string" doesn't work as I expected. You just can't put it like this.

content: `my es6 string <strong>template</strong>` 

How I solved it:

const template = (`my es6 string <strong'>${variable}</strong>`);
content: {
      element: 'p',
      attributes: {
        innerHTML: `${template}`,
      },
    }

There is no documentation how to do this, it was pure trial and error, but at least seems to work.

Shnigi
  • 972
  • 9
  • 19
4

Use SweetAlert's html setting.

You can set output html direct to this option:

var hh = "<b>test</b>";
swal({
    title: "" + txt + "", 
    html: "Testno  sporocilo za objekt " + hh + "",  
    confirmButtonText: "V redu", 
    allowOutsideClick: "true" 
});

Or

swal({
    title: "" + txt + "", 
    html: "Testno  sporocilo za objekt <b>teste</b>",  
    confirmButtonText: "V redu", 
    allowOutsideClick: "true" 
});
Silvio Delgado
  • 6,798
  • 3
  • 18
  • 22
4

There's sweet Alert version 1 and 2. Actual version 2 works with HTML nodes.

I have a Sweet Alert 2 with a data form that looks this way:

<script>
 var form = document.createElement("div");
      form.innerHTML = `
      <span id="tfHours">0</span> hours<br>
      <input style="width:90%;" type="range" name="tfHours" value=0 step=1 min=0 max=25
      onchange="window.changeHours(this.value)"
      oninput="window.changeHours(this.value)"
      ><br>
      <span id="tfMinutes">0</span> min<br>
      <input style="width:60%;" type="range" name="tfMinutes" value=0 step=5 min=0 max=60
      onchange="window.changeMinutes(this.value)"
      oninput="window.changeMinutes(this.value)"
      >`;

      swal({
        title: 'Request time to XXX',
        text: 'Select time to send / request',
        content: form,
        buttons: {
          cancel: "Cancel",
          catch: {
            text: "Create",
            value: 5,
          },
        }
      }).then((value) => {
        console.log(value);
      });

 window.changeHours = function (value){
   var tfHours = document.getElementById("tfHours");
   tfHours.innerHTML = value;
 }
 window.changeMinutes = function (value){
   var tfMinutes = document.getElementById("tfMinutes");
   tfMinutes.innerHTML = value;
 }

Have a go to the Codepen Example!

gtamborero
  • 2,898
  • 27
  • 28
3

I know that my answer may come in too late, but i found a fix that works for me.

  1. Create an object to hold in your html content

var html_element = '<p><code>This</code> is an error</p>';

  1. Then proceed on to create your sweet alert element
swal({
    title: "My Title", 
    text: "",  
    html: true,  
    confirmButtonText: "Okay" 
});
  1. Use javascript setTimeout function to append your html into the sweet alert. I found that setting the timeout to 210 works well

    setTimeout(function(){
         $('.sweet-alert p:eq(0)').html(html_element)
    },210);
    

And You have done it!

Kario Kevo
  • 51
  • 3
1

All you have to do is enable the html variable to true.. I had same issue, all i had to do was html : true ,

    var hh = "<b>test</b>"; 
swal({
        title: "" + txt + "", 
        text: "Testno  sporocilo za objekt " + hh + "",  
        html: true,  
        confirmButtonText: "V redu", 
        allowOutsideClick: "true"  
});

Note: html : "Testno sporocilo za objekt " + hh + "",
may not work as html porperty is only use to active this feature by assign true / false value in the Sweetalert.
this html : "Testno sporocilo za objekt " + hh + "", is used in SweetAlert2

Ad Kahn
  • 551
  • 4
  • 6
0

You can use compiled elements at hidden div and get the div by id and put like this:

  var wrapper = document.getElementById('yourdiv');
    swal({
      icon: "sucess",
      text: "Your Content",
      content: wrapper
    })
-11

I assume that </ is not accepted inside the string.

Try to escape the forward slash "/" by preceding it with a backward slash "\" for example:

var hh = "<b>test<\/b>";
Crystal
  • 5,960
  • 4
  • 21
  • 27