javascript - Post variables not set when submitting a form with JS -
i have form submit javascript user clicks label. there weird behavior datas not posted. if submit form delay (even delay of 0) works.
here 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 use following line values won't set form.submit() // if use `settimeout` works, delay of 0 settimeout(function() { form.submit() }, 0) }) </script> it's not big issue can make work settimeout writing delay of 0 ugly. thought browser bug tested chrome , firefox , have same result.
any idea happening?
this because you're listening on label click. try listening checkbox click.
$('input[type=checkbox]').click(function() { $(this).closest('form').submit(); }); clicking on label means browser "click" associated element. , since you're submitting form on label click, won't give browser chance this.
why settimeout 0 work, because trick post execution untill browser done current actions. can find more info on @ why settimeout(fn, 0) useful?
Comments
Post a Comment