user1257255
user1257255

Reputation: 1171

JavaScript & jQuery: Change variable and check value

I have problem with JavaScript/jQuery. I'm trying to change variable's value after dialog is displayed and if checbox is checked, but this don't work when I check value of it. What can I do instead or this code is wrong?

HTML:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8" />
  <title>JS/jQuery</title>
  <link rel="stylesheet" type="text/css" href="style.css">
  <script type="text/javascript" src="jquery-1.8.2.min.js"></script>
  <script type="text/javascript" src="myjs.js"></script>
</head>
<body>
  <div class="back"></div>
  <div class="start">   
    <label for="chex">Is this checkbox checked?</label>
    <input type="checkbox" id="checkexist" name="chex" />
    <button id="run">Run form</button>
  </div>
  <div class="window"></div>
</body>
</html>

JavaScript:

$(document).ready(function() {

  var start = false;
  var check = false;

  if (start == false) {
    $("#checkexist").click(function(){
        if (this.checked) {
            check = true;
        }
    });
    $("#run").click(function(){
        start = true;
        $(".start").fadeOut('slow', function(){
            $(".start").css("display", "none");
        });
        $(".back").fadeOut('slow', function(){
            $(".back").css({'display' : 'none', 'opacity' : '0', 'filter' : 'alpha(opacity=0)'});
        });
    });
  } else {
    if (check == true) {
        $(".window").click(function(){
            $(".window").hide('fast');
        });
    } else {
        //do something
    }
  }
});

Upvotes: 0

Views: 4493

Answers (1)

Rafael Herscovici
Rafael Herscovici

Reputation: 17094

ok, so lets try solving this bit by bit.

your code runs inside $(document).ready(function() {}); and as you were told by others, if (start == false) {} this part will never run: else{}, since when the page loads, start will be always set to false (var start = false;) next,

$("#checkexist").click(function(){
        if (this.checked) {
            check = true;
        }
    });

could be replace with: $('#checkexist').is('checked') which will return true or false based on the checkmark. true for checked, false for unchecked.

now, assuming we know that, and we know you want to run this when the button is clicked:

$('#run').on('click', function(){
    // close the start and back
    $(".start,.back").fadeOut('slow');
    if ($('#checkexist').is(':checked'))
    {
        // checkbox is checked, close the .window
        $(".window").hide('fast');
    }else{
        //checkbox was not checked, what to do?
    }
});

Had a small syntax error. it work fine now. You can see it work here : http://jsfiddle.net/fp7kV/8/

sorry, missed the :

Upvotes: 1

Related Questions