var form = document.getElementById('my-form')
var submitBtn = form.querySelector('[type="submit"]')
submitBtn.disabled = true
form.addEventListener('input', function () {
submitBtn.disabled = !form.checkValidity()
})
But yes as @TechnoBear says get your markup sorted first, otherwise it may not even work. Putting the <script> tag inside the form itself is also not right⌠Iâm surprised it actually works with the inline submit handler. Anyway, put all your scripts to the end of the page before the closing </body> tag, or if the script must be present before the body of the page, inside the head.
@m3g4p0p your code was good but about my code . It was special. You know in that code when any one leave blank the textbox then automatically change the background of textbox in red and show alert in text below rhe textbox. But in your given code it was only for disabled function. Could you add the both code in my JavaScript.
My above snippet would work alongside yours without problem⌠although you could simplify this a lot by also using the constraint validation API. I happened to give an example in another thread only yesterday. :-) E.g. you could add an error class to the invalid element like so:
var form = document.getElementById('my-form')
var submitBtn = form.querySelector('[type="submit"]')
submitBtn.disabled = true
form.addEventListener('input', function (event) {
var target = event.target
target.classList.toggle('error', !target.validity.valid)
submitBtn.disabled = !form.checkValidity()
})
As seen in the examples above, each time the user tries to submit an invalid form, the browser displays an error message. The way this message is displayed depends on the browser.
These automated messages have two drawbacks:
There is no standard way to change their look and feel with CSS.
They depend on the browser locale, which means that you can have a page in one language but an error message displayed in another language.
âŚ
To customize the appearance and text of these messages, you must use JavaScript; there is no way to do it using just HTML and CSS.
âŚ
If you want to take control over the look and feel of native error messages, or if you want to deal with browsers that do not support HTMLâs built-in form validation, you must use JavaScript.
* example code can be found on the MDN page linked to
But isnât that what your original code is doing? And if you disable the submit button until the whole form is valid (as per your original request), further client-side validation on submit would be redundant⌠;-) hereâs a fiddle that demonstrates the technique from post #5 (slightly modified to also show error messages).
I didnât see anything in that jsfiddle last night, and Iâm still not seeing anything in it today. So I canât know what problem(s) youâre having.
If you can post minimal examples of the HTML, CSS and JavaScript that you are working with here Iâll be glad to help further.