Edon Freiner
Edon Freiner

Reputation: 596

detecting if checkbox was checked

I had an assignment to make a To Do list in HTML/JS/CSS

I am allowed to make any aesthetic changes as I want as long as it has 3 things: a button that allows the user to input to the list, removing the button when there is no input (white space is not considered input) and the user should be able to click on something so the user can delete the task.

I was thinking of a check box that was clicked for more than 5 seconds. so far I got this:

<!DOCTYPE html>
<html lang="en">

<head>
    <link rel="stylesheet" href="ToDo.css" type="text/css" />
    <script src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
    <script src="ToDo.js"></script>
</head>


<body>
<h1>ToDo</h1>
<input type="checkbox"/>
<input type="text" placeholder="Please Enter a Task" id="input">
<input type="submit" value="Add" id="addButton" hidden="hidden">


</body>


</html>

And this is my JS file:

$(document).ready(function() {

    $("#input")[0].oninput = function isEmpty() {

        if ($("#input").val() == "") {
            $("#addButton").fadeOut(250);
        } else {
            $("#addButton").fadeIn(250);
        }
    }


    $("#addButton").click(function() {
        $("#addButton").after($("<p></p>").text($("#input").val()));
        //$("p:first").prepend('<input type="checkbox" value="102" name="tags[]" id="tag102" class="checkbox" />');
        $("#input").val("");
        $("#addButton").hide();
    });




    $('input[type=checkbox]').change(function() {
      if( $(this).is(':checked')) {
              alert("This passed");
          }else {
              alert("This failed");
          }


    });

});

I have a CSS files as well, but I am assuming that isn't important at the moment. I havn't started with the timer because I couldn't figure out how to check if the check box was checked. I tried using a regular HTML check box to check it out and that worked fine. but for some reason the ones crated through java script aren't working.

Please help, Thank you.

Upvotes: 0

Views: 2870

Answers (4)

nnnnnn
nnnnnn

Reputation: 150080

"having checked the checkbox, nothing will happen unless the user doesn't uncheck it within 5 seconds"

The keys to implementing that sort of functionality (which, as I noted in a comment above will provide a non-standard user experience, so I don't recommend doing it other than for learning purposes) are the setTimeout() function, which lets you schedule a function to be called after a specified delay, and the clearTimeout() function, which lets you cancel a previously scheduled timeout. You'd use them with a checkbox event handler as follows:

var timeoutId;
$("input[type=checkbox]").on("click", function(e) {
  if (this.checked) {
    timeoutId = setTimeout(function() {
      alert("Time up! Do something here...");
    }, 5000); // delay in milliseconds
  } else {
    clearTimeout(timeoutId);
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<label><input type="checkbox"> Check me (and wait five seconds, or uncheck me)</label>

Note that for checkboxes I would recommend using the click event rather than the change event, because in some older browsers "clicking" the checkbox via the keyboard does not result in a change event until the user tabs out of the field, whereas a click event will be triggered by mouse- or keyboard-based changes to the checkbox. Also, given that within the event handler this refers to the checkbox, you can use this.checked directly, no need for $(this).prop("checked") or $(this).is(":checked").

Also, given you'll have list items added dynamically, you will want to handle checkbox events with a delegated event handler bound to a parent element that does exist when the page loads (the document, in your case, since you have no container divs or anything). That is:

// instead of:
$("input[type=checkbox]").on("click", function() { ... })
// use delegated version:
$(document).on("click", "input[type=checkbox]", function() { ... })

Putting that together with your other code (and reducing the delay to three seconds instead of five, for ease of testing):

$(document).ready(function() {
    $("#input").on("input", function isEmpty() {
        if ($.trim(this.value) === "") {
            $("#addButton").fadeOut(250);
        } else {
            $("#addButton").fadeIn(250);
        }
    });

    $("#addButton").click(function() {
        $("#addButton").after($("<p></p>").text($("#input").val()));
        $("p:first").prepend('<input type="checkbox" />');
        $("#input").val("");
        $("#addButton").hide();
    });

    $(document).on('click', 'input[type=checkbox]', function() {
        if (this.checked) {
            // use an arrow function to solve the "this" problem
            var timeoutId = setTimeout(() => {
                $(this).parent().remove();
            }, 3000); // delay in milliseconds
            
            // store the timeout id against the element itself, because
            // the user could click multiple checkboxes in the list
            $(this).data("timeoutId", timeoutId);
        } else {
            clearTimeout($(this).data("timeoutId"));
        }
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<h1>ToDo</h1>
<input type="text" placeholder="Please Enter a Task" id="input">
<input type="submit" value="Add" id="addButton" hidden="hidden">

Upvotes: 0

Pato Salazar
Pato Salazar

Reputation: 1477

Just detect the existence of the checked property like this:

    $('input[type=checkbox]').change(function() {
      if( $(this).prop('checked')) {
              alert("This passed");
          }else {
              alert("This failed");
          }
    });
});

It should work :)

Upvotes: 1

Santiago Hern&#225;ndez
Santiago Hern&#225;ndez

Reputation: 5646

Use .on() to attach an event handler function for dynamic created elements

$(document).on('change','input[type=checkbox]', function() {
      if ($(this).is(':checked')) {
          alert("This passed");
      } else {
          alert("This failed");
      }
});

$(document).ready(function() {
    $(document).on('change','input[type=checkbox]', function() {
          if ($(this).is(':checked')) {
              alert("This passed");
          } else {
              alert("This failed");
          }
    });
});
<!DOCTYPE html>
<html lang="en">

<head>
    <link rel="stylesheet" href="ToDo.css" type="text/css" />
    <script src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
    <script src="ToDo.js"></script>
</head>


<body>
<h1>ToDo</h1>
<input type="checkbox"/>
<input type="text" placeholder="Please Enter a Task" id="input">
<input type="submit" value="Add" id="addButton" hidden="hidden">


</body>


</html>

Upvotes: 0

yaakov
yaakov

Reputation: 4685

Use the .prop() function:

$('input[type=checkbox]').change(function() {
      if( $(this).prop('checked') == "checked") {
              alert("This passed");
          }else {
              alert("This failed");
          }


    });

Upvotes: 0

Related Questions