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:

<p>
        <label for="image_info">Information</label>
        <br>
        <input type="text" name="image_info" id="image_info">
    </p>

    <br>

    <button type="button" onclick="imageErrorMessage()">Check</button>

    <script type="text/javascript">
        function imageErrorMessage(image_info){
        if(image_info === "")document.getElementById('image_info').setCustomValidity('Please enter your information.');
        else document.getElementById('image_info').setCustomValidity('')
        }
    </script>

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

function imageErrorMessage(image_info){
  if(image_info == "") {
    document.getElementById('image_info').setCustomValidity('Please enter your information.');
    document.getElementById('image_info').reportValidity();
  } else {
    document.getElementById('image_info').setCustomValidity('')
    document.getElementById('image_info').reportValidity();
  }
}
<p>
  <label for="image_info">Information</label>
  <br>
  <input type="text" name="image_info" id="image_info">
</p>
<br>
<button type="button" onclick="imageErrorMessage(document.getElementById('image_info').value)">Check</button>
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement