Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript

Tried with a different approach and not working. Can anyone help?

Hi there,

so Treasure used the following code to prevent a download in case the checkbox is not checked.

$pdfs.on("click", function(event) {
  if ($(":checked").length === 0) {
     event.preventDefault();
     alert("Please check the checkbox"); 
  }
});

I tried a different approach (see below), but it's not working. I get the alert box with the checkbox being checked or unchecked.

$pdfs.on("click", function(event) {
  const $checked = $("input").checked
    if (!$checked) {
      event.preventDefault();
      alert("Please check the box");    
    }
});

Can anyone help?

1 Answer

I think it is because $("input") returns an array/NodeList of all <input>s instead of a single instance, and the .checked property needs to be attached to a single instance. I just dumped your code into CodePen to try it out, and if you just make a slight tweak, it seems to work:

$pdfs.on("click", function(event) {
  const $checked = $("input")[0].checked // <-- specify that you only want to test the first (0-indexed) instance of <input> in the array of nodes matching $("input")
    if (!$checked) {
      event.preventDefault();
      alert("Please check the box");    
    }
});

When I did that, the alert popped up when the box was unchecked, and didn't when the box was checked. See if that works for you.

Thanks!! That makes sense.