somanyerrorswhy somanyerrorswhy - 4 months ago 15
jQuery Question

How do I set a character limit in sweetalert?

$(document.getElementById("buttonClicked")).click(function(e) {
swal({
imageUrl: "http://www.petdrugsonline.co.uk/images/page-headers/cats-master-header",
title: "sentence: ",
text: "0/140",
type: "input",
showCancelButton: true,
closeOnConfirm: true,
closeOnCancel: true,
}, function(text) {

if (inputValue.length > 140) {
swal.showInputError("You need to write something!");
}
// fire post
$.post("/index.php", {
img: finalDataURL,
text: text
}).done(function(data) {

});

});
});


I want to modify it so that the text will update for each character typed inside the input (0/140 -> 1/140 -> 2/140 -> etc) and I want to make it so that if the user tries clicking submit and the # amount of characters they typed exceed 140, an error pops up.

Right now my code isn't doing any of that.

Answer

Currently, SweetAlert doesn't have a character counter built in so you'd have to tweak the source code a bit to get what you want.

For the error, you were on the right track, just missing a few things and some logic:

...
function(text) {

    // check the length of "text" instead of "inputValue"
    // since that's what you're passing into the function

    if (text.length > 140) {
        swal.showInputError("You have exceeded 140 characters!");
        return false;
    } else {
       // Only try submitting once character count validation has passed
        $.post("/index.php", {
            img: finalDataURL,
            text: text
        }).done(function(data) {

        });
    }
 });