Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery: check if variable is defined after keyup() function

Am creating register form with jquery function keyup(), for example if input is correct I assign it to a txtuname variable,then I press register button and I need to know that all form variables are correct and defined.Code below is not working:

<script type="text/javascript">      
$("document").ready(function() {
  $("#txtuname").keyup(function() {
    if ($("#txtuname").val().length < 6) {
      jQuery("label[for='txtuname']").text("user name is too short");
    }
    if ($("#txtuname").val().length >= 6) {
      var txtuname = $("#txtuname").val();
      jQuery("label[for='txtuname']").text("");
    }
  });
  $("#submitRegistration").click(function() {
    if (typeof txtuname == 'defined') {
      alert("defined");
    }
    if (typeof txtuname == 'undefined') {
      alert("undefined");
    }
  });
});
</script>
like image 372
Darius92 Avatar asked Oct 15 '25 14:10

Darius92


1 Answers

Modified code. Main point of this code is that txtuname should be visible in both scopes of keyup event listner and click listner. So if there are more lements, create Validation object and just check whether all the values was set and correct. And yes, use or $ or jQuery in your code.

$("document").ready(function(){

    var txtuname = null;

    $("#txtuname").keyup(function(){
        if($("#txtuname").val().length<6){
            jQuery("label[for='txtuname']").text("user name is too short");
        }

        if($("#txtuname").val().length>=6){
            txtuname=$("#txtuname").val();
            jQuery("label[for='txtuname']").text("");
        }
    });

    $("#submitRegistration").click(function(){
        if( txtuname == null || txtuname.length < 6)  ){
            alert("incorrect");
        }
        else{
            alert("correct");
        }

    });
});

Updated check of variable using comment of @Rhumborl , thx

like image 77
xAqweRx Avatar answered Oct 18 '25 09:10

xAqweRx



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!