Reputation: 3583
I have this simple form for my websites search (Wordpress)
<form action="/" method="get">
<label for="search">Search</label>
<input type="text" name="s" id="search" value="<?php the_search_query(); ?>" />
<input type="image" class="search-btn" alt="Search" src="<?php bloginfo( 'template_url' ); ?>/img/magnifier13.png" width="16" height="16" />
</form>
I don't want people to be able to search for anything without putting less than 2 characters in the search field, How do I go about doing this? preferably with JS.
Upvotes: 0
Views: 2669
Reputation: 3885
$('#SubmitButtonId').Click(function(){
var myLength = $("#search").val().length;
if(myLength < 3)
{
//show message
}
else
{
//submit form
}
});
Upvotes: 0
Reputation: 56
You can simply do something like this:
<form action="/" method="get">
<label for="search">Search</label>
<input type="text" name="s" id="search" value="<?php the_search_query(); ?>" />
<input type="image" class="search-btn" alt="Search" src="<?php bloginfo( 'template_url' ); ?>/img/magnifier13.png" width="16" height="16" />
<input type='button' onclick='checkBeforeSubmit();'>
</form>
// somewhere in your javascript code:
var checkBeforeSubmit = function(){
var text = $("#search").val();
if(text.length > 2)
$(form).submit();
}
Upvotes: 0
Reputation: 1229
Using JavaScript you can check for the length of the search text box and see if it is more than 2 characters. If it's more than 2, then go ahead with the search:
document.getElementsByClassName('test').onClick =function(){
if(document.getElementById('search').text.length <= 2){
alert("Needs more than two characters to do search);
else{
// commence search
}
});
Upvotes: 0
Reputation: 20469
You can use the forms onsubmit
event to prevent submission if the length is less than the defined amount:
<form action="/" method="get" onsubmit="return (this.s.value.length > 2);">
<label for="search">Search</label>
...
Upvotes: 0
Reputation: 2148
You can simply call a javascript code for checking the length of textbox before submitting form.
<form action="/" method="get" onsubmit="return (document.getElementById('search').value.length > 2);">
Upvotes: 1
Reputation: 3488
You can use the pattern
attribute of HTML5. The required
attribute is also needed, otherwise an input field with an empty value will be excluded from constraint validation.
<input pattern=".{2,}" required title="2 characters minimum">
<input pattern=".{3,10}" required title="3 to 10 characters">
Upvotes: 8