You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

点击提交按钮获取表单ID、AJAX提交及表单嵌套<tr>的实现问题

Answers to Your Questions

1. How to Get the Form ID When Clicking the Submit Button

Your current approach using $(this).closest("form[id]").attr('id') is totally valid—as long as your button is nested inside the form element and your HTML structure follows valid specs. The closest() method climbs up the DOM tree to find the nearest parent form with an ID, then attr('id') grabs that ID value for you.

2. Can You Put a Form Inside a <tr> Tag? How to Implement the AJAX POST?

Nope, placing a <form> directly inside a <tr> is invalid HTML. <tr> elements can only have <td> or <th> as direct children, and browsers will often render this incorrectly, breaking your jQuery selectors and functionality. Here’s how to fix this and implement your AJAX POST properly:

Valid HTML Structure Options

Choose the one that fits your use case:

Option 1: Wrap Each Row’s Form in a Spanning <td>

If each table row is a separate form, use a <td> with colspan to cover all columns, then nest the form inside it. You can style the inputs to look like they’re in separate cells:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table border="1">
  <tr>
    <td colspan="2">
      <form id='idForm1'>
        <span style="display:inline-block; width:120px;">
          <input type="text" name="username" placeholder="Username">
        </span>
        <span style="display:inline-block; width:100px;">
          <button type="button">Submit</button>
        </span>
      </form>
    </td>
  </tr>
  <tr>
    <td colspan="2">
      <form id='idForm2'>
        <span style="display:inline-block; width:120px;">
          <input type="text" name="email" placeholder="Email">
        </span>
        <span style="display:inline-block; width:100px;">
          <button type="button">Submit</button>
        </span>
      </form>
    </td>
  </tr>
</table>

Option 2: Use HTML5’s form Attribute (Link Elements to an External Form)

If you want to keep your table structure intact, define the form outside the table, then use the form attribute on inputs and buttons to link them to the form by ID:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id='idForm' style="display:none;"></form>
<table border="1">
  <tr>
    <td><input type="text" name="username" placeholder="Username" form="idForm"></td>
    <td><button type="button" form="idForm">Submit</button></td>
  </tr>
</table>

Updated jQuery Code for AJAX POST

Here’s the modified code to get the form ID, collect input values, and send them via POST:

$("button").click(function(e) {
  e.preventDefault();
  
  // Get the form element (handles both nested and linked forms)
  let $form = $(this).closest("form");
  if (!$form.length) {
    // Fallback for forms linked via the HTML5 form attribute
    const linkedFormId = $(this).attr("form");
    $form = $(`#${linkedFormId}`);
  }
  const formId = $form.attr('id');
  
  // Collect all input values from the form (automatically encodes data)
  const formData = $form.serialize();
  
  // Send the AJAX POST request
  $.ajax({
    url: "your-target-endpoint", // Replace with your actual API/script URL
    type: "POST",
    data: formData,
    success: function(response) {
      console.log("Submission successful!", response);
      alert(`Form ${formId} submitted successfully!`);
    },
    error: function(xhr, status, error) {
      console.error("Submission failed:", error);
      alert(`Oops, failed to submit form ${formId}.`);
    }
  });
});

Quick Tips:

  • serialize() is a huge time-saver—it automatically collects all input values from the form into a URL-encoded string, perfect for POST requests.
  • The fallback for the form attribute ensures your code works no matter which HTML structure you choose.
  • Always include error handling in AJAX calls to catch network issues or server errors.

内容的提问来源于stack exchange,提问作者gigakas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 03:50:39