提交按钮失效问题咨询:同页定义正常,外部JS定义动作失效
Hey there! Let's break down why your submit button stops working when you move the handler to a separate JS file, and walk through the fixes:
1. DOM Loading Order Is Probably the Main Issue
When your separate JS file loads before the page's DOM (specifically your #submit button) is fully rendered, your code tries to attach an event listener to an element that doesn't exist yet. This makes the binding fail silently (or throw an error in your browser console).
Fix for this:
Wrap your event binding code in a listener that waits for the DOM to be fully ready. Here's how to do it with vanilla JS:
document.addEventListener('DOMContentLoaded', function() { const submitBtn = document.getElementById('submit'); submitBtn.addEventListener('click', function(e) { e.preventDefault(); // Add this if you're handling submission manually // Your submit logic goes here }); });
If you're using jQuery (common in ASP.NET MVC projects), use this instead:
$(document).ready(function() { $('#submit').on('click', function(e) { e.preventDefault(); // Your submit logic goes here }); });
2. You've Got Nested Forms (A Hidden Invalid Markup Issue!)
Looking at your code, there's an outer <form method="post"> wrapping the form generated by Html.BeginForm. HTML does not allow nested forms—browsers will render this incorrectly, which can completely break submit behavior.
On top of that, your submit button is currently outside the form created by Html.BeginForm. A submit button outside a form won't trigger that form's submission by default, even if the nesting wasn't an issue.
Fix for this:
Remove the outer form tag and move your submit button inside the Html.BeginForm block:
<div id="sjfb"> <div id="form-fields"> @using (Html.BeginForm("Index", "Home", FormMethod.Post)) { @Html.DisplayFor(model => model.controls); @Html.DisplayFor(model => model.formEditor); <!-- Submit button is now inside the correct form --> <button type="submit" id="submit" class="submit">Save Form</button> } </div> </div>
Quick Troubleshooting Checks
- Open your browser's DevTools (F12) → Console tab. If you see errors like "Cannot read properties of null (reading 'addEventListener')", that confirms the DOM loading order problem.
- Use the Elements tab to inspect the rendered HTML—make sure there are no nested forms and your submit button is inside the form generated by
Html.BeginForm.
内容的提问来源于stack exchange,提问作者Iswarya

