CodexBloom - Programming Q&A Platform

HTML form submission with data attributes causing advanced patterns in modern browsers

👀 Views: 74 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-05
html javascript form JavaScript

I'm maintaining legacy code that Quick question that's been bugging me - I'm working with an scenario when trying to submit a form that contains input elements with custom `data-*` attributes. When I click the submit button, the form is not submitting, and I see the following behavior in the console: `Uncaught TypeError: want to read properties of null (reading 'value')`. I have a simple HTML form set up as follows: ```html <form id='myForm'> <input type='text' data-custom='example' id='input1' /> <input type='submit' value='Submit' /> </form> ``` In my JavaScript, I'm trying to access the value of `input1` when the form is submitted: ```javascript document.getElementById('myForm').addEventListener('submit', function(event) { event.preventDefault(); // Prevent default submission const inputValue = document.querySelector('[data-custom]').value; console.log(inputValue); }); ``` I ensured the JavaScript runs after the DOM has fully loaded, either by placing it at the bottom of the body or using `DOMContentLoaded`. However, I still face this scenario on Chrome 92 and Firefox 89. I've verified that the selector is correct, and the input field exists in the DOM when the form is submitted. I've tried using both `getElementById` and `querySelector`, but both methods yield the same behavior. I also checked if any CSS styles might be hiding the input field or preventing it from being recognized, but everything appears fine. Does anyone have insights into why this might be happening, or if there are any known issues with data attributes and form submissions in modern browsers? I'd really appreciate any guidance on this. I'm developing on Ubuntu 20.04 with Javascript. Any suggestions would be helpful.