I have looked all over the internet to solve this but can't find any answers. If I am not clear, here is what I want to remove:
Example code:
<form action="search.html" id="form">
<input type="text" placeholder="Search..." name="s" id="s" required>
<button type="submit">Submit</button>
</form>
Also, for the <input type="">
, is it better to put type="search"
rather than type="text"
for what I'm doing?
If anything other than HTML needs to be used, no jquery if possible please.
CodePudding user response:
You can use setCustomValidity
:
<form action="search.html" id="form">
<input type="text" placeholder="Search..." name="s" id="s" oninvalid="this.setCustomValidity(' ')" required>
<button type="submit">Submit</button>
</form>
I'm not sure why you have to specify a space (" "
) as the validity message, but it apparently gets ignored if you apply an empty string.
CodePudding user response:
If you want it to act like Google, then you can listen for the submit
event on the form, and then use .preventDefault()
to prevent the form from submitting. See https://stackoverflow.com/a/8664535/1499877 for another example.
form = document.getElementById('form');
form.addEventListener('submit', function(event) {
event.preventDefault(); // prevent the form from submitting
});
<form id="form">
<input type="search" id="nosubmit" />
<button>
Submit?
</button>
</form>
Another option with slightly better user experience is to disable the button by default, and then enable it when the text input field has some value. This at least provides the user with a little feedback (the button becomes enabled) when they enter something in the input field.
input = document.getElementById('nosubmit');
button = document.getElementById('button');
input.addEventListener('input', function(event) {
if (this.value == "") {
button.disabled = true;
} else {
button.disabled = false;
}
});
<form id="form">
<input type="search" id="nosubmit" />
<button id="button" disabled>
Submit?
</button>
</form>