jQuery form submission when form nested in table

2020-04-16 06:42发布

Is there a reason why forms won't submit using jQuery inside tables or am I just doing something wrong? I've tested the form submission outside a table, then soon as i wrapped it inside a table it stopped working, even though I added an extra parent() to make up for the form moving above the <td> element within the code. Could anybody be able to help me out with this issue please?

HTML

WITHOUT TABLE
<form action="page.cfm" method="post">
    <select class="select">
        <option>Test</option>
    </select>
</form>

WITH TABLE
<table>
    <tr>
        <form action="page.cfm" method="post">
            <td>
                <select class="select">
                    <option>Test</option>
                </select>
            </td>
        </form>
    </tr>
</table>

jQuery

WITHOUT TABLE
$(".select").on("change", function() {
    $(this).parent("form").submit();
});

WITH TABLE
$(".select").on("change", function() {
    $(this).parent().parent("form").submit();
});

3条回答
不美不萌又怎样
2楼-- · 2020-04-16 06:53

HTML

<form action="page.cfm" method="post">
    <table>
        <tr>
            <td>
                <select class="select">
                    <option>Test</option>
                </select>
            </td>
        </tr>
    </table>
</form>

JS

$(".select").on("change", function() {
    this.form.submit();
});

note that for form elements this.form references the containing form.

查看更多
家丑人穷心不美
3楼-- · 2020-04-16 07:03

Is there a reason why forms won't submit using jQuery inside tables or am I just doing something wrong?

Your HTML is invalid. Use a validator. A form can contain an entire table. A form can be contained entirely in a table cell. A form cannot contain only some cells that make up a table.

Error correction in the browser is putting the form outside the table, so trying to submit it gives unexpected results.

查看更多
混吃等死
4楼-- · 2020-04-16 07:10

Try using $.closest()

WITHOUT/WITH TABLE

$(".select").on("change", function() {
    $(this).closest("form").submit();
});
查看更多
登录 后发表回答