What is the difference between this.click() and $(this).click()?

javascript, jquery, jquery-events

Solution

The fact that counter is going up gave me the clue that there is a link between checked attribute, which you are using, and firing the click event manually.

I searched Google for 'jquery checkbox click event raise' and found this link, where author faces the exact same problem and the workaround he used.

http://www.bennadel.com/blog/1525-jQuery-s-Event-Triggering-Order-Of-Default-Behavior-And-triggerHandler-.htm

On a side note, I think you can simplify your code further:

$j('input[type=checkbox].vote_item').click( 
function() 
{
    var maxNumberOfChoices = 5;

    //get number of checked checkboxes. 
    var currentCheckedCount = $j('input[type=checkbox].vote_item :checked');

    if(currentCheckedCount > maxNumberOfChoices)
    {
        //It's useful if you show how many choices user can make. :)
        alert('You can only select maximum ' + maxNumberOfChoices + ' checkboxes.');
        return false;
    }

    return true;
});

Problem

In the end, I have decided that this isn't a problem that I particularly need to fix, however it bothers me that I don't understand why it is happening. Basically, I have some checkboxes, and I only want the users to be able to select a certain number of them. I'm using the code below to achieve that effect. ``` $j( function () { $j('input[type=checkbox].vote_item').click( function() { var numLeft = (+$j('#vote_num').text()); console.log(numLeft); if ( numLeft == 0 && this.checked ) { alert('I\'m sorry, you have already voted for the number of items that you are allowed to vote for.'); return false; } else { if ( this.checked == true ) { $j('#vote_num').html(numLeft-1); } else { $j('#vote_num').html(numLeft+1); } } }); }); ``` And when I was testing it, I noticed that if I used: ``` $j('input[type=checkbox]').each( function () { this.click() }); ``` The JavaScript reacted as I would expect, however when used with: ``` $j('input[type=checkbox]').each( function () { $j(this).click() }); ``` It would actually make the counter count UP. I do realize that it isn't the most secure way to keep count using the counter, however I do have server side error-checking that prevents more than the requisite amount from being entered in the database, that being the reason that I have decided that it doesn't actually need fixing. Edit: The `$j` is due to the fact that I have to use jQuery in `noConflict` mode...

Original source