Reputation: 289
I am trying to run a jQuery function when a user types in more than 5 characters in a text box. So far I've managed to get my script to run using the keyup function, however this causes the script to run the moment the user types in the very first character and I only want it to run when the user has typed in 5 or more characters.
Here's my code, I'm brand new to jquery so would really appreciate it if someone could please show me where I am going wrong with this. thanks in advance,
<script type="text/javascript">
$(function() {
//alert('Document is ready');
$('#search').keyup(function() {
if ($("#search").val().length > 3)
var sel_stud = $(this).val();
//alert('You picked: ' + sel_stud);
$.ajax({
type: "POST",
url: "include/fetch_search.php",
data: 'theOption=' + sel_stud,
success: function(whatigot) {
//alert('Server-side response: ' + whatigot);
$('#search_results').html(whatigot);
$('#theButton').click(function() {
alert('You clicked the button');
});
} //END success fn
}); //END $.ajax
})}; //END dropdown change event
}); //END document.ready
</script>
Upvotes: 2
Views: 4315
Reputation: 1287
You need to have checked in for 5 rather 3
if ($("#search").val().length >=5)
And this line
})}; //END dropdown change event
should be modified to this
}); //you just added an extra } at the end
I guess rest is fine
Upvotes: 1
Reputation: 3023
$(function() {
$('#search').keyup(function (e) {
if($(this).val().length >= 5)
alert('5th character entered');
})
}); //END document.ready
also remove extra ending curly-brace from code:
}); //END dropdown change event
instead of
})}; //END dropdown change event
Upvotes: 0
Reputation: 1413
Try this. You forgot to put the keys on the if statement.
<script type="text/javascript">
$(function() {
//alert('Document is ready');
$('#search').keyup(function () {
if($("#search").val().length > 5) {
var sel_stud = $(this).val();
$.ajax({
type: "POST",
url: "include/fetch_search.php",
data: 'theOption=' + sel_stud,
success: function(whatigot) {
//alert('Server-side response: ' + whatigot);
$('#search_results').html(whatigot);
$('#theButton').click(function() {
alert('You clicked the button');
});
} //END success fn
}); //END $.ajax
}
})}; //END dropdown change event
}); //END document.ready
</script>
This is what you had:
if($("#search").val().length > 3)
That if statement won't do anything, you have to wrap some code inside it, that's what the code above does (and changed the 3 for a 5 :S).
Upvotes: 2