简体   繁体   中英

Form submitting with jquery error

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..

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;}
    });
});

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM