Reputation: 456
First, thanks for taking the time to look at my question. Really. This is my question. I'm making a fancybox search page for a website I'm making. Getting the search results in fancybox all work fine.
But if the visitor just clicks on search
it returns every item on the site. What I would like is make the form so, that the visitor has
to at least enter 3 characters before the search does a search. If the visitor doesn't enter 3 or more characters fancybox will give an alert saying please enter at least 3 or more characters
.
I've looked around stackoverflow and found this code:
$( document ).ready(function() {
input_value = $.trim($('#searchkey').val());
if(input_value == ''){
alert('Enter some value');
return false; //Does not submit the form
}else{
//perform your code if it should not be empty.
}
});
So I placed my code inside the correct place, like so:
$( document ).ready(function() {
input_value = $.trim($('#str').val());
if(input_value == ''){
alert('Enter some value');
return false; //Does not submit the form
} else {
$(function() {
$('#search').on('submit', function(e) {
e.preventDefault();
jQuery.fancybox({
width: 600,
height: 600,
openEffect: 'fade',
closeEffect: 'fade',
href: 'search-post-results.php',
type: "ajax",
ajax: {
type: "POST",
data: {
value: $('#str').val()
}
}
});
});
});
}
});
I'm not getting any syntax errors, but if I reload the page it gives me the correct alert. But thats if there are no
characters entered. So I've changed this line:
if(input_value == ''){
to:
if(input_value == '2'){
Figuring that I should set a value. But that does nothing. Does anyone have a similar script/snippet that does the same? Or know why this isn't working?
Here is the HTML (nothing special there):
<form id="search">
<table>
<tr>
<td>
<input type="text" name="s" id="str" placeholder="Search...">
</td>
<td>
<button class="btn form-button btn-default">
<i class="fa fa-search"></i>
</button>
</td>
</tr>
</table>
</form>
Thans again for your time.
Upvotes: 0
Views: 153
Reputation: 670
Try this , Also Please change validation position because if you reload then always alert will show . So you can validate after submit action.
$(function() {
$('#search').on('submit', function(e) {
e.preventDefault();
if(input_value.length < 3 ){
// Show your alert message.
}else{
// Here you start Ajax Request.
}
});
});
Upvotes: 1
Reputation: 11297
Use length
property.
if( input_value.length < 3 ){
// error message if characters are less than 3
} else {
// continue the search
}
Upvotes: 3