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 Swal.fire({
      title: 'Multiple inputs',
      html:
        '<input oninput="myMethod" id="swal-input1" class="swal2-input">' +
        '<input id="swal-input2" class="swal2-input">',
      focusConfirm: false,
      preConfirm: () => {
        return [
          document.getElementById('swal-input1').value,
          document.getElementById('swal-input2').value
        ]
      }
    })
    JavaScript Anonymous, Jul 3, 2019

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



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

    document.addEventListener('input', myMethod);

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

    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);

    Swal.fire({
    html: (
    <div>
    <input onInput={console.log} id="swal-input1" className="swal2-input">
    <input id="swal-input2" className="swal2-input">
    </div>
    ),
    });




    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!