I need to populate a select list based on the information input on a form text inplut field. I got the Ajax part figured out but it does not work as expected. The idea is as the user typing in the first name field, the select list will populate the appropriate options. The function does work but the var firstname = $(“#fn”).val(); call will always return one character less than the content typed in the field.
Any help will be appreiated!
Below is the relevent html and code:
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#fn").keypress(function() {
var firstname = $("#fn").val();
$.get("CustomerList", {FirstName: firstname}, function(responseText) {
$("#div1").text(responseText);
});
});
});
</script>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Show all names</title>
</head>
<body>
<form method="GET" action='Controller' name="CreateNTF" >
<table>
<tr>
<td>Create User:</td>
<td><input id="fn" type="text" name="FirstName" /></td>
<td><input id="ln" type="text" name="LastName"/></td>
</tr>
<tr>
<td>Carrier</td>
<td>
<span id="div1"></span>
</td>
</tr>
</table>
<input type="submit" name="submit" value="Submit" onClick="return validateForm();"/>
</form>
</body>
</html>
Try using
keyupinstead ofkeypress. Maybekeypressfires too early to let.val()recognize the text change.Another solution would be to calculate the final string by yourself:
But finally, this guy seems to have the same problem as you, and the suggested solution was also the same.