多行输入表单仅含一个提交按钮,如何实现日期字段逐行非空校验?
The issue you're facing happens because of two main problems: duplicate id attributes across your date inputs, and your validation function only targeting one specific element (the last one with that id in the DOM). Here's how to fix it properly:
Step 1: Update Your HTML to Avoid Duplicate IDs
First, remove the duplicate id="l" from your date input (since IDs must be unique across the entire page). We'll use the existing class input_l to target the correct field instead:
<td> <input name="l" class="input_l" type="date" value="{{ data.l }}"> </td>
Then, modify the submit button's onclick handler to pass a reference to itself. This lets our validation function know which row's date field to check:
<td> <button class="btn btn-primary btn-sm" onclick="return checkDate(this);" style="width: 60px">submit</button> </td>
Step 2: Rewrite the Validation Function
Replace your existing IsEmpty() function with this one. It uses the button reference to find the corresponding date input in the same row:
<script> function checkDate(button) { // Get the parent row (<tr>) of the clicked button const row = button.closest('tr'); // Find the date input within this specific row const dateInput = row.querySelector('.input_l'); if (dateInput.value === "") { alert("Date cannot be empty for this row"); return false; // Prevent form submission } return true; // Allow submission if date is filled } </script>
Why This Works
button.closest('tr')finds the nearest parent table row of the clicked button, so we're only looking at the row the user is trying to submit.row.querySelector('.input_l')targets the date input specifically within that row, avoiding any confusion with other rows.- No more duplicate IDs, which is both valid HTML and ensures we're checking the right field every time.
Bonus: Fix Invalid HTML Structure
Quick note: Wrapping <tr> elements directly inside <form> tags within a <tbody> is technically invalid HTML (tbody can only contain tr elements). A cleaner approach is to wrap each row's content in a form that spans all columns using colspan, or place the form inside a single td. For example:
<tr> <td colspan="12"> <form class="form-signin" action="{{ url_for('user.work1',id=data.id) }}" method="post" name="frm"> <!-- All your row inputs here --> <button class="btn btn-primary btn-sm" onclick="return checkDate(this);" style="width: 60px">submit</button> </form> </td> </tr>
This makes your HTML valid and avoids potential rendering issues, though your current setup might work in most browsers.
内容的提问来源于stack exchange,提问作者hakukou

