简体   繁体   中英

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?

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?

Somebody (I can't remember his username) posted the solution, but got downvoted so he removed his answer. But his solution was right so here it is:

All I need to do is use the click event on the input instead of the label

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

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