Skip to content
Advertisement

Button that generates error message on condition

I am trying to implement a button in HTML that calls a function on click, which checks whether a textinput is empty. If so (the information hasn’t been entered), an error message for the input field should be generated.

I am experimenting with a button that doesn’t submit the form. However, if you have a solution with a button that does submit the form (unless the string is empty), I’ll gladly take it. In that case (and in any really) I would like to work with setCustomValidity, as I want an error message right away and not after the page reloads if that makes sense (because then the input in the form isn’t kept).

This is what I have so far:

JavaScript

Unfortunately something seems to be missing/wrong, as it doesn’t work. I’m fairly new to Javascript so the mistake could be crystal clear and I wouldn’t know.

Thanks very much!

Advertisement

Answer

There were three problems:

  • you were missing a lot of curly braces for the if statements (note: apparently these aren’t required, but I prefer them for readability)
  • you need to put document.getElementById('image_info').reportValidity(); after the setCustomValidity
  • you weren’t sending any parameters to imageErrorMessage

JavaScript
JavaScript
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement