prevent refresh of page when button inside form clicked

前端 未结 13 1825
终归单人心
终归单人心 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:21

    A javascript method to disable the button itself

    document.getElementById("ID NAME").disabled = true;
    

    Once all form fields have satisfied your criteria, you can re-enable the button

    Using a Jquery will be something like this

    $( "#ID NAME" ).prop( "disabled", true);
    
    0 讨论(0)
  • 2020-11-22 05:23

    All you need to do is put a type tag and make the type button.

    <button id="btnId" type="button">Hide/Show</button>

    That solves the issue

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

    Add type="button" to the button.

    <button name="data" type="button" onclick="getData()">Click</button>
    

    The default value of type for a button is submit, which self posts the form in your case and makes it look like a refresh.

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

    Return function is not working in all the cases. I tried this:

    <button id="Reset" class="Button-class" onclick="return Reset()">Show result</button>
    

    It didnt work for me.

    I tried to return false inside the function and it worked for me.

    function Reset()
    {
        .
        .
        .
        return false;
    }
    
    0 讨论(0)
  • 2020-11-22 05:24

    You can use ajax and jquery to solve this problem:

    <script>
        function getData() {
            $.ajax({
                url : "/urlpattern",
                type : "post",
                success : function(data) {
                    alert("success");
                } 
            });
        }
    </script>
    <form method="POST">
        <button name="data" type="button" onclick="getData()">Click</button>
    </form>
    
    0 讨论(0)
  • 2020-11-22 05:25
    <form method="POST">
        <button name="data" onclick="getData()">Click</button>
    </form>
    

    instead of using button tag, use input tag. Like this,

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