How to add textarea tag as input element in sweet alert using jQuery

Prafull Pol picture Prafull Pol · Jun 13, 2016 · Viewed 17.4k times · Source

I don't understand how to add a textarea type in sweet alert. Similar to type: "input"

$('#saveBtn).click(function(){
    swal({   
        title: "Enter your Name!",  
        text: "your name:",  
        type: "input",   
        showCancelButton: true,   
        closeOnConfirm: false, 
        showLoaderOnConfirm: true,
        animation: "slide-from-top",   
        inputPlaceholder: "Write something" }, 
        function(inputValue){  
             if (inputValue === false) 
                 return false;    
             if (inputValue === "") {
                swal.showInputError("You need to write something!");  
                return false
                }
            swal("Nice!", "You wrote: " + inputValue, "success"); 
         });
});

This works fine. But if I use type: "textarea" instead of type: "input"

This gives error like this:

sweetalert.min.js:1 Uncaught ReferenceError: logStr is not defined

Thanks for help.

Answer

Pranav C Balan picture Pranav C Balan · Jun 13, 2016

You can't use textarea as a type since the sweetalert does not support that.

The type of the modal. SweetAlert comes with 4 built-in types which will show a corresponding icon animation: "warning", "error", "success" and "info". You can also set it as "input" to get a prompt modal. It can either be put in the object under the key "type" or passed as the third parameter of the function.(Taken from here)


Instead you can use html markup with text option by setting html option true. But in this way you can't get value inside the textarea as callback variable. For that give an id to the textarea and get value using that.

swal({
  title: "Enter your Name!",
  text: "<textarea id='text'></textarea>",
  // --------------^-- define html element with id
  html: true,
  showCancelButton: true,
  closeOnConfirm: false,
  showLoaderOnConfirm: true,
  animation: "slide-from-top",
  inputPlaceholder: "Write something"
}, function(inputValue) {
  if (inputValue === false) return false;
  if (inputValue === "") {
    swal.showInputError("You need to write something!");
    return false
  }
  // get value using textarea id
  var val = document.getElementById('text').value;
  swal("Nice!", "You wrote: " + val, "success");
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/1.1.3/sweetalert.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/1.1.3/sweetalert-dev.js"></script>