Marc Rasmussen
Marc Rasmussen

Reputation: 20555

HTML Button redirects pages

I have the following button:

<div class="form-group">
    <button onclick="assign_all()" class="btn btn-default">Vælg alle</button>
</div>

Now this calls a JavaScript function called assign_all

This works fine however when it is done executing the JavaScript it simply tries to load a page. Which is fairly odd (its like if you click on an A tag)

As you can see below nothing in my javaScript indicates that it should reload / load a page:

function assign_all() {

    var info = [];
    var i = 0;
    $('.user_list').each(function () {
        if ($(this).hasClass('show')) {
            info[i] = $(this).find('.user_id').val();
            i++;
        }
    })
}

Can anyone tell me why this is happening?

Upvotes: 5

Views: 125

Answers (3)

Dhiraj Wakchaure
Dhiraj Wakchaure

Reputation: 2706

you can do this also

<button onclick="assign_all();return false;" class="btn btn-default">Vælg alle</button>

Upvotes: 0

Nick Mehrdad Babaki
Nick Mehrdad Babaki

Reputation: 12485

Add type="button" to your button tag. it must solve the issue

Upvotes: 1

James Donnelly
James Donnelly

Reputation: 128781

It's because the default button element's type attribute is set to submit. Your button element is attempting to submit a form. Simply give it a type of button:

<button onclick="assign_all()" class="btn btn-default" type="button">...</button>

Upvotes: 12

Related Questions