MTurk人群模板提交验证求助:自定义JS验证代码失效
Hey there! I’ve dealt with this exact issue when working on MTurk surveys—let’s break down why your code isn’t working and how to fix it.
Common Issues & Solutions
1. The Submit Button ID Might Not Be submitButton
MTurk’s default submit button doesn’t use submitButton as its ID. It’s usually an <input> element with type="submit", or has a different ID like submit.
First, use your browser’s dev tools (F12 → Elements tab) to inspect the button and confirm its actual selector. Then replace your selector with something more reliable, like:
const submitBtn = document.querySelector('input[type="submit"]');
2. Use addEventListener Instead of setAttribute
Directly setting the onclick attribute can get overwritten by MTurk’s native scripts that run after your code. Event listeners are more robust and less likely to be overridden. Here’s the updated code:
document.addEventListener('DOMContentLoaded', function() { const submitBtn = document.querySelector('input[type="submit"]'); if (submitBtn) { // Bind the validation function to the click event submitBtn.addEventListener('click', validateForm); } }); function validateForm(e) { // Prevent the default submit action first e.preventDefault(); alert("test"); // If your validation passes, uncomment this to submit the form manually: // document.getElementById('mturk_form').submit(); }
3. Use DOMContentLoaded Instead of window.onload
window.onload waits for all resources (images, stylesheets) to load, which might be too late—MTurk’s scripts could have already attached their own submit handlers by then. DOMContentLoaded fires as soon as the HTML is parsed, ensuring your code runs earlier.
4. Confirm the Form’s ID
If you need to manually submit the form after validation, MTurk’s main survey form typically has the ID mturk_form, so document.getElementById('mturk_form').submit() will work once your checks pass.
Why Your Original Code Failed
Most likely, either:
- Your
getElementById('submitButton')returnednull(since the button doesn’t have that ID), so no event was bound. - MTurk’s own JavaScript overwrote the
onclickattribute after your code ran, bypassing your validation.
内容的提问来源于stack exchange,提问作者Mr.cysl

