Flex_able
Flex_able

Reputation: 35

get value of var in jQuery

is it possible to get the var codeError by function ? I need to post this value to a variable $code in php.

$(document).ready(function() {
    $('#cognome').bind( 'blur',  function(){
        var cog = $(this).val();
        if(cog == "" || cog.length<=2) {
            $('#chkCognome' ).addClass("invalid").removeClass("valid"); 

            var codeError=1;
        } else {
            $('#chkCognome').addClass("valid").removeClass("invalid");  

            var codeError=0;
        }
    });
});

Upvotes: 1

Views: 135

Answers (3)

aahhaa
aahhaa

Reputation: 2275

<html>
     <form action="error.php" method="post">
          <input type="hidden" value="0" name="code">
     </form> 
</html>    

<script>
     $(document).ready(function() {

          var codeError = $(input).val(0); 

          if(error) { $(input).val(1); }

     })
</script>

you need to define codeError outside of if else statement, better yet you don't really need a else statement. if you need to pass it to php just use <form>

Upvotes: 2

Ervis Trupja
Ervis Trupja

Reputation: 2800

You need to declare it outside the scope of bind() function. It would look something like:

$(document).ready(function() {

    var codeError; //Declare outside the scope of the function.

    $('#cognome').bind( 'blur',  function(){
        var cog = $(this).val();
        if(cog == "" || cog.length<=2) {
            $('#chkCognome' ).addClass("invalid").removeClass("valid"); 

            codeError=1;
        } else {
            $('#chkCognome').addClass("valid").removeClass("invalid");  

            codeError=0;
        }
    });
});

Upvotes: 4

Soviut
Soviut

Reputation: 91525

You need to declare codeError outside of the if statement, and potentially outside of your event binding as well, depending on what level you want it to be accessible at.

var codeError; // accessible within all subsequent functions and event handlers

$('#cognome').on('blur',  function(){
    if (cog === '') {
        codeError = 1;
    }
    else {
        codeError = 0;
    }
});

Upvotes: 2

Related Questions