Home > Software engineering >  why does listener on button behave differently than listener on form (both to event submit)
why does listener on button behave differently than listener on form (both to event submit)

Time:10-25

I have a form to enquire a price. The price is returned via an Ajax (is it - not sure?) request and then the submit button within the same form is displayed.

Just staying with the first enquiry button, if I use formQuote.addEventListener('submit', (event) => { the price is loaded and the 2nd button is displayed. If, however, I use btnPricecheck.addEventListener('submit', (event) => { as shown below, the page reloads, removing all entered data (note formQuote vs btnPricecheck before addEventListener). It is the 5th code line.

const formQuote = document.querySelector('#quote');
  if (formQuote) {
     btnPricecheck = document.getElementById('btn-pricecheck');
     btnEnquiry = document.getElementById('btn-enquiry');
      btnPricecheck.addEventListener('submit', (event) => {
            event.preventDefault();
        
            fromDate = formQuote.elements["fromDate"].value;
            toDate = formQuote.elements["toDate"].value;
            apptmnt = $('input[name="apptmnt"]:checked').val();

            parameters = '';
            if (fromDate) parameters  = 'fromDate='   fromDate;
            if (toDate) parameters  = '&toDate='   toDate;
            if(apptmnt) { 
                if (parameters.length > 1) {
                    parameters  = '&apptmnt='   apptmnt
                }
                else {
                    parameters  = 'apptmnt='   apptmnt
                }
            }
    console.log( parameters);
            
            $('#priceDisplay').load('forms/quote.php?'   parameters);
            if (document.getElementById('total'))
                showPersonForm();
            window.scrollTo(0,document.body.scrollHeight);
      });

      btnEnquiry.addEventListener('submit', (event) => {
            // disable default action
            event.preventDefault();
            
            var cpFields = ['surname', 'firstName', 'email', 'street', 'zip', 'city', 'country', 'phone', 'notes'];
            for (var fld in cpFields) {
                document.getElementById("c_" fld).value = document.getElementById(fld).value;
            }                       
            // configure a request
            const xhr = new XMLHttpRequest();
            xhr.open('POST', 'forms/confirmation.php');         
            // Define what happens on successful data submission
            xhr.addEventListener( 'load', function( event ) {
              alert( 'Yeah! Data sent and response loaded.' );
              console.log(xhr.responseText);
            } );            
            // Define what happens in case of error
            xhr.addEventListener(' error', function( event ) {
              alert( 'Oops! Something went wrong.' );
              console.log(xhr.responseText);
            } );
            // prepare form data
            let data = new FormData(formQuote);     
            // send request
            xhr.send(data);     
            // listen for `load` event
            xhr.onload = () => {
                console.log(xhr.responseText);
            }
      });
  }
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

UPDATE: what I noticed, fromDate = formQuote.elements["fromDate"].value; can hardly work here, but fromDate = document.getElementById["fromDate"].value;doesn't, either

CodePudding user response:

In second case event handler just does not run, so event.preventDefault() is neither executed so browser sends your form to URL its (I mean, <form>'s) action attribute(that might be just current page's address if you have not specified any). And it looks like "page reloads and data is cleared".

Why this happens? Because button does not trigger submit event, so handler you attach is never being called.

Though, you can set up event handler upper in the tree, than it(event) is actually happens. Say, you could put submit event handler on <body> and it would be executed due to event bubbling. But since bubbling never happens to lower elements(children), but only to higher(parents) it would not help you here.

  • Related