Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Post variables not set when submitting a form with JS

I have a form I submit with javascript as soon as the user clicks a label. There is a weird behavior where the datas are not posted. But if I submit the form with a delay (even with a delay of 0) it works.

Here is the html:

<form action="/other-page" method="post">
    <input id="val-1" type="checkbox" name="filter[]" value="1">
    <label for="val-1">Value 1</label>

    <input id="val-2" type="checkbox" name="filter[]" value="2">
    <label for="val-2">Value 2</label>
</form>

The script:

<script>
    $('label').click(function() {
        var form = $(this).closest('form')

        // if I use the following line the values won't be set
        form.submit()

        // If I use a `setTimeout` it works, even with a delay of 0
        setTimeout(function() {
             form.submit()
        }, 0)
    })
</script>

It's not a big issue as I can make this work with the setTimeout but writing this with a delay of 0 is really ugly. I thought about a browser bug but I tested with Chrome and Firefox and I have the same result.

Any idea about what is happening?

like image 731
romainberger Avatar asked Oct 21 '22 10:10

romainberger


1 Answers

This is because you're listening on the label click. Try listening for checkbox click.

$('input[type=checkbox]').click(function() {
    $(this).closest('form').submit();
});

Clicking on a label means the browser will "click" the associated element. And since you're submitting the form on label click, it won't give the browser the chance to do this.

Why setTimeout with 0 does work, is because this is a trick to post the execution untill the browser is done with its current actions. You can find more info on this at Why is setTimeout(fn, 0) sometimes useful?

like image 143
sroes Avatar answered Oct 27 '22 22:10

sroes