Javascript override form onsubmit event not working

前端 未结 4 1321
粉色の甜心
粉色の甜心 2021-01-12 20:20

I am overriding a form submit event like this:

form.onsubmit = function(event) {
  event.preventDefault();

But when I call submit on the fo

相关标签:
4条回答
  • 2021-01-12 20:43

    Try with this one

    form.submit = function() {
      //event.preventDefault();     No need of this call
      //do your processing here
    }
    
    0 讨论(0)
  • 2021-01-12 20:55

    Following on @garryp's answer on "return false". To add on, further reading from MDN event.stopImmediatePropagation to see differences and use case between event.preventDefault and event.stopPropagation.

    On the side note, "return false;" is the same calling both;

      event.preventDefault();
      event.stopPropagation();
    

    Hope this helps.

    0 讨论(0)
  • 2021-01-12 20:59

    As Manish pointed out, both overriding the submit function and calling the submit form in javascript was complicating how the event was propagating. So added a hidden button in to the form in javascript and called the button's click function instead of the form submit function. WHich seems to have worked even it it feels rather like a kludge! Many thanks for to all of you for your prompt help. :-)

    function nameFileLabel(id)
    {
        var f = document.getElementById('fileForm' + id);
        var l = document.getElementById('fileText_' + id);
        var i = document.getElementById('fInputId' + id);
        var b = document.getElementById('sub' + id);
        if (i.value != '')
        {
            l.innerHTML = i.value.replace('fakepath', '...');
            var theUploadForm = document.getElementById('fileDiv_' + id);
            theUploadForm.style.visibility = 'visible';
            theUploadForm.style.display = 'block';
            b.click();
        }
    }
    
    0 讨论(0)
  • 2021-01-12 21:03

    To prevent the form posting your function must return false.

    form.onsubmit = function(event) {
        event.preventDefault();
        return false;
    }
    
    0 讨论(0)
提交回复
热议问题