Reputation: 25
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!
Upvotes: 1
Views: 2664
Reputation: 4808
Some errors in your code:
<form>
.My solution:
<form>
const $form = document.getElementById('form')
const $submit = document.getElementById('submitButton')
const $imageInfo = document.getElementById('image_info')
$submit.onclick = (event) => {
event.preventDefault()
if (!$imageInfo.value) {
$imageInfo.setCustomValidity('Please enter your information.')
$imageInfo.reportValidity()
} else {
$form.submit()
}
}
* {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol';
}
<form id="form">
<label for="image_info">Information:</label>
<input type="text" name="image_info" id="image_info">
<button id="submitButton">Submit</button>
</form>
Upvotes: 1
Reputation: 989
There were three problems:
document.getElementById('image_info').reportValidity();
after the setCustomValidityimageErrorMessage
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>
Upvotes: 1