prevent refresh of page when button inside form clicked

前端 未结 13 1914
终归单人心
终归单人心 2020-11-22 04:58

I have an issue while using buttons inside form. I want that button to call function. It does, but with unwanted result that it refresh the page.

My simple code goes

相关标签:
13条回答
  • 2020-11-22 05:27

    For any reason in Firefox even though I have return false; and myform.preventDefault(); in the function, it refreshes the page after function runs. And I don't know if this is a good practice, but it works for me, I insert javascript:this.preventDefault(); in the action attribute .

    As I said, I tried all the other suggestions and they work fine in all browsers but Firefox, if you have the same issue, try adding the prevent event in the action attribute either javascript:return false; or javascript:this.preventDefault();. Do not try with javascript:void(0); which will break your code. Don't ask me why :-).

    I don't think this is an elegant way to do it, but in my case I had no other choice.

    Update:

    If you received an error... after ajax is processed, then remove the attribute action and in the onsubmit attribute, execute your function followed by the false return:

    onsubmit="functionToRun(); return false;"

    I don't know why all this trouble with Firefox, but hope this works.

    0 讨论(0)
  • 2020-11-22 05:28

    This one is the best solution:

    <form  method="post"> 
        <button  type="button" name="data" onclick="getData()">Click Me</button>
    </form>
    

    Note: My code is very simple.

    0 讨论(0)
  • 2020-11-22 05:29

    The problem is that it triggers the form submission. If you make the getData function return false then it should stop the form from submitting.

    Alternatively, you could also use the preventDefault method of the event object:

    function getData(e) {
        e.preventDefault();
    }
    
    0 讨论(0)
  • 2020-11-22 05:31

    Let getData() return false. This will fix it.

    <form method="POST">
        <button name="data" onclick="return getData()">Click</button>
    </form>
    
    0 讨论(0)
  • 2020-11-22 05:32

    HTML

    <form onsubmit="return false;" id="myForm">
    </form>
    

    jQuery

    $('#myForm').submit(function() {
        doSomething();
    });
    
    0 讨论(0)
  • 2020-11-22 05:37

    I was facing the same problem. The problem is with the onclick function. There should not be any problem with the function getData. It worked by making the onclick function return false.

    <form method="POST">
        <button name="data" onclick="getData(); return false">Click</button>
    </form>
    
    0 讨论(0)
提交回复
热议问题