Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

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.