简体   繁体   中英

Page refreshes when hitting a simple button?

everyone. As you can see i've a form with a button inside. When clicking on the button i want to execute some JavaScript code (not important for this question).

When i'm hitting the delete button, my page refreshes but that's not what i want. Do you guys know why my page refreshes when hitting the button?

HTML CODE

<form id="form" method="POST"> 
    <button type="button "id="delete" name="delete" onclick="delete_data();"><i class="fa fa-remove" aria-hidden="true"></i> Delete Zone(s)</button>
</form>

Javascript Code

function delete_data(){
        //this function is used to obtain id's of selected checkboxes.

        var checkedIds = $(".chk:checked").map(function() {
            return this.id;
        }).toArray();

        alert(checkedIds);
    }

You should prevent the default behavior of happening:

function delete_data(event){
        event.preventDefault();
        //this function is used to obtain id's of selected checkboxes.

        var checkedIds = $(".chk:checked").map(function() {
            return this.id;
        }).toArray();

        alert(checkedIds);
    }

event.preventDefault() will help to stop the default behaviour.

function delete_data(){
   event.preventDefault();
    var checkedIds = $(".chk:checked").map(function() {
        return this.id;
    }).toArray();

    alert(checkedIds);
}

e.preventDefault() will prevent the default event from occuring. That's mean it prevents any default browser actions from being executed.

You should add e.preventDefault() as the first line in the handler.

function delete_data(event){
        event.preventDefault();

        //...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM