Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Question mark in URL after closing alert box

I have a dummy Bootstrap modal with a very simple JS alert meant to be triggered when the submit button is clicked. The code is live here and this is what it looks like:

<div class="modal fade" id="contact" role="dialog" >
<div class="modal-dialog">
    <div class="modal-content">
        <form class="form-horizontal" role="form" name="contact-form">
            <div class="modal-header">
                <h4>test</h4>
            </div>
            <div class="modal-body"><p>This is body</p></div>
            <div class="modal-footer">
                <button type="submit" id="submit" class="btn btn-primary btn-lg" onclick="alert('something');">Send</button>
            </div>
        </form>
    </div>
</div>

If you visit the site, you can trigger the modal by clicking on the contact link in the top navigation menu. The modal looks like this:

enter image description here

As you can see, there's just one field and a submit button. The button's onclick() event is set to alert the word "something" on the screen. This works fine except that when you close the alert, the page refreshes with a "?" appended to the URL. How do I prevent this refresh and where does the question mark come from?

like image 792
TheLearner Avatar asked Jul 03 '16 00:07

TheLearner


1 Answers

At first I thought that it happens because the button has property type set to submit, so I'd recommend to remove this property completely, and the trailing question mark would probably not appear anymore. But it does.

What really needs to be done is event default action has to be prevented. To do that, return false right there in the onclick event callback function:

<button onclick="alert('something'); return false;">...</button>

This way you, well, return false, and this is perceived as if you want to prevent further execution of the click event, effectively submit operation.

like image 73
rishat Avatar answered Nov 15 '22 01:11

rishat