AJAX on click rather on keyup

I have a script below that is currently working by waiting on the keyup of an input field, its not working very well because its very unreliable in that it can result in the value being checked without it grabbing the full word in the input field, basically more often than not its not searching using the full word entered into the input field.

So Im wondering if its better to use the option that the user first fills the full word in and then clicks a button to activate the function below, so could someone help me convert it from what it is to a call the function on button click after entering the value into the input filed.

$(document).ready(function() {
$("#username").keyup(function (e) {
	$(this).val($(this).val().replace(/\s/g, ''));
	var username = $(this).val();
	if(username.length < 4){$("#user-result").html('');$('#submitNew').css('visibility', 'hidden');return;}
	if(username.length >= 4){
		$("#user-result").html('<img src="images/ajax-loader.gif" />');
		$.post('check_username.php', {'username':username}, function(data) {
		  $("#user-result").html(data);
		});
	}
 });	
});

<input type="text" name="userName" id="username" size="50" value="<?php echo $uName;?>" />

Or you could do it on blur. But, even then, thatā€™s not a guarantee that the full word is in place.

:slight_smile:

Thatā€™s when they leave isnā€™t it, so no I donā€™t think that will work as they have to wait to get the nod that the username is free before continuing.

This is saying ā€œon keyup of input field with id of ā€˜usernameā€™, do the following:ā€

If you create a button and give it an id of ā€˜chkUsernameā€™, you can set the onclick of chkUsername to check the value of id ā€˜usernameā€™.

$(document).ready(function() {
$("#chkUsername").click(function (e) {
	$("#username").val($("#username").val().replace(/\s/g, ''));
	var username = $("#username").val();
	if(username.length < 4){$("#user-result").html('');$('#submitNew').css('visibility', 'hidden');return;}
	if(username.length >= 4){
		$("#user-result").html('<img src="images/ajax-loader.gif" />');
		$.post('check_username.php', {'username':username}, function(data) {
		  $("#user-result").html(data);
		});
	}
 });	
});

<input type="text" name="userName" id="username" size="50" value="<?php echo $uName;?>" />

Not exactly. The blur event is triggered when they leave that field - that is when their proposed username has been completely entered. It is in fact the earliest point at which you can meaningfully test whether the value they entered is already taken.

Thank you for all the help, and have a very good username check option, very nice indeed, love it

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.