there is a registration form, I check if the username is available or not. If available then appears a text next to the username field into a paragraph ("Available!"), if not then ("Not available!"). I don't want to be submitted if the username is not available.
<script type ="text/javascript">
$(function(){
$('#usernameFeedback').load('check.php').show();
$('#usernameID').keyup(function(){
$.post('check.php',{username:registration.username.value},
function(result){
$('#usernameFeedback').html(result).show();
var feedVar = $('#usernameFeedback').text();
});
});
});
</script>
<script>
$(document).ready(function(){
$("#regForm").submit(function(){
alert("HELLO"); // works fine
if ( $('#usernameFeedback').text() == "Not available!" )
return;
event.preventDefault();
});
});
</script>
With this code doesn't work properly (I am new to jquery), doesn't stay in the current page if the username is not available..
2 Answers 2
Pass the event to the function.
$("#regForm").submit(function(){
should be
$("#regForm").submit(function(event){
And use the return false in the same line as the if, since you are not using {}
Try this code:
$(document).ready(function () {
$("#regForm").submit(function (event) {
event.preventDefault();
alert("HELLO"); // works fine
if ($('#usernameFeedback').text() == "Not available!") {return false;}
});
});
Comments
an if() statement without curly brackets will only listen the first and only statement below it. If you include the curly brackets, you can have multiple statements, like below:
if ( $('#usernameFeedback').text() == "Not available!" ) {
event.preventDefault();
return false;
} else {
return true;
}
Furthermore, the event.preventDefault() won't ever execute with your current code, as the function is left before it's even able to execute, thus I've swapped those around, it's prevented by Default, then returned.
And Sergio quickly and rightly mentions, add event to function, to even allow you to event.preventdefault() in the first place!
1 Comment
.text() content of #usernameFeedback because it can be modified by the user. Instead, try storing the server response in a variable, e.g. var usernameAvailability and assign it a value of true or false based on the server response. Prior to form submission, you can evaluate this variable and determine if the submission should proceed or not.