How to add HTML input into sweet alert?

24,071

Solution 1

SweetAlert2 supports radio inputs out of the box: https://sweetalert2.github.io/#input-radio

Swal.fire({
  title: 'Select color',
  input: 'radio',
  inputOptions: {
    '#ff0000': 'Red',
    '#00ff00': 'Green',
    '#0000ff': 'Blue'
  },

  // validator is optional
  inputValidator: function(result) {
    if (!result) {
      return 'You need to select something!';
    }
  }
}).then(function(result) {
  if (result.isConfirmed) {
    Swal.fire({
      icon: 'success',
      html: 'You selected: ' + result.value
    });
  }
})
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

Solution 2

Default sweetalert's stylesheet hides all input fields in alerts, so you have to restore initial values:

.sweet-alert input {
   display: initial;
   width: auto;
   height: auto;
   margin: auto;
}
Share:
24,071
b22
Author by

b22

Updated on May 16, 2021

Comments

  • b22
    b22 about 3 years

    I am trying to add radio button into dialog box using sweet alert but I'm not able to do it. Following is the code:

    swal({
            title: "<small>Please select an reason to cancel this job !</small>",
            type: "warning",
            text:"<input type=\"radio\" name=\"reason\" value=\"male\">Reason 1<br><input type=\"radio\" name=\"reason\" value=\"female\">Reason 2<br><input type=\"radio\" name=\"reason\" value=\"female\">Other Reason",
            showCancelButton: true,
            confirmButtonColor: "#DD6B55",
            confirmButtonText: "Yes",
            cancelButtonText: "No",
            closeOnConfirm: false,
            closeOnCancel: false,
            html: true
        },
                function(isConfirm){
                    if (isConfirm) {
                        swal("Result !","Job cancelled successfully.");
                    } else {
                        swal("Cancelled  !", "Process aborted");
                    }
                });
    
  • b22
    b22 almost 9 years
    where i need to add this ? into my css file or sweetalert.css ?
  • Michał Perłakowski
    Michał Perłakowski almost 9 years
    It's up to you. Unless you get sweetalert.css from CDN, you can just replace the rule in .sweet-alert input from display: none; to display: inline-block;.
  • b22
    b22 almost 9 years
    do you know about this error if yes then could you please help me out. stackoverflow.com/questions/32070945/…
  • Alvaro
    Alvaro over 8 years
    Still not working for checkbox values. They get transformed into text input elements.
  • Michał Perłakowski
    Michał Perłakowski over 8 years
    @Alvaro cannot reproduce, could you give a link to a JS Fiddle reproducing this issue?