Search code examples
javascripthtmlnode.jsbootstrap-4sweetalert

How can I allow numeric only in Swal Sweetalert


I wanted to know how could I allow only numeric on this part.

  {
    title: "Dollar Amount?",
    text: "How much is your Dollar Question worth?",
    inputPlaceholder: "Enter Amount"
  }

I'm using a Sweetalert plugin . It's been bugging me for days and I'm just new to front-end, I'm really a full backend guy.

function showDollarQuestion() {

if (inUserId === "" || inUserId === null) {
    socket.emit('stud notif', myuserid,myuserid,"noroom");
}else{
    swal.setDefaults({
      input: 'text',
      confirmButtonText: 'Next →',
      showCancelButton: true,
      animation: false,
      progressSteps: ['1', '2']
    })

    var steps = [
      {
        title: "Dollar Question?",
        text: "Ask a question to your influencer",
        inputPlaceholder: "Write your Dollar Question"
      },
      {
        title: "Dollar Amount?",
        text: "How much is your Dollar Question worth?",
        inputPlaceholder: "Enter Amount"
      }
    ]

    swal.queue(steps).then(function (result) {
        if (result[1] === "" || result[1] === "") {
            swal.resetDefaults()
                swal({
                title: 'Empty Field!',
                html:
                  'Dollar Question is required<br />Dollar Amount is required',
                confirmButtonText: 'Try Again',
                showCancelButton: false
            })
        }else if(){

        }else{
            swal.resetDefaults()
            swal({
                title: 'All done!',
                html:
                  'Your Dollar Question is '+JSON.stringify(result[0]).replace(/\"/g, "")+
                  '<br /> Dollar Question worth is '+JSON.stringify(result[1]).replace(/\"/g, ""), 
                confirmButtonText: 'Great, your question has been successfully submitted to your influencer',
                showCancelButton: false
            })
            socket.emit('dollar quest', JSON.stringify(result[0]).replace(/\"/g, ""), JSON.stringify(result[1]).replace(/\"/g, ""), inUserId, myuserid, 'dquest');

        }
    }, function () {
      swal.resetDefaults()
    })
}
}

So far this is all the code I got. And I can't find any tutorial about this Sweetalert thing. Thanks in advance guys


Solution

  • First of all, you are using SweetAlert2, not SweetAlert. Those are 2 different projects with slight differences in API.

    In order to make numeric field you should set the input parameter to 'number':

    Swal.fire({
      text: 'How much is your Dollar Question worth?',
      input: 'number'
    }).then(function(result) {
      if (result.value) {
        const amount = result.value
        Swal.fire(amount + ' USD')
      }
    })
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

    For more details about the input parameter see the official documentation page: https://sweetalert2.github.io/