How to assign a processing method to input in Sweetalert2?

  • 0
    I need to put my own handler on input in Sweetalert2 plugin.
    But html is displayed there as a line, so if you just write oninput = "myMethod", and the method is defined just above, then it does not work.
    const myMethod = (e) => console.log(e)
    const { value: formValues } = await{
      title: 'Multiple inputs',
        '<input oninput="myMethod" id="swal-input1" class="swal2-input">' +
        '<input id="swal-input2" class="swal2-input">',
      focusConfirm: false,
      preConfirm: () => {
        return [
    JavaScript Anonymous, Jul 3, 2019

  • 1 Answers
  • 0
    You can listen for document-level events:

    const myMethod = event => {
    if ( && === 'swal-input1') {
    // Поймали событие "input" для элемента #swal-input1

    document.addEventListener('input', myMethod);

    const { value: formValues } = await{/* . . . */});

    document.removeEventListener('input', myMethod);

    By the way, if you are using ReactJS then you can use sweetalert2-react-content . With it, you will have the ability to use ReactJS components as HTML, in which you can do anything, including custom event handlers attached to specific elements. You can do something like this:

    import SwalRaw from "sweetalert2";
    import withReactContent from 'sweetalert2-react-content';

    const Swal = withReactContent(SwalRaw);{
    html: (
    <input onInput={console.log} id="swal-input1" className="swal2-input">
    <input id="swal-input2" className="swal2-input">

    Swal is invoked as usual, but you can additionally use ReactJS components for options such as: title , html , confirmButtonText , denyButtonText , cancelButtonText , footer , and closeButtonHtml .
    Adam Reeves

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!