• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

146
Views
Jquery - If each() .filter working on console but not in code in realtime

Context: I have a gallery of images. The user can select each image, when they click it, the "selected" attribute is added to the individual element and a new class is added to their chosen image. The thing is, I want to limit this to only 2 selections being available.

I want to edit my script to only run up until the length is 2 or less. If the length reaches 2, no more Selected attributes to be added and no more class changes to be toggled.

I feel like I'm close. Right now my users can select/deselect but they can just do it too many times. Where am I going wrong?

function NFTSelector() {

$("#NFTGallery2 > img").each(function() {
    $(this).on("click", function() {
      
      if($(this).filter("[selected]").length>=2) {
        alert('true');
    } else 
        console.log("less than 2 or undefined so letting them choose more");
     {
            $(this).toggleClass('chosenNFT');

            if ($(this).attr('selected')) {
                $(this).removeAttr('selected');
            } else {
                $(this).attr('selected', 'selected');
            }

            
        }
    })
});
}

almost 3 years ago · Juan Pablo Isaza
1 answers
Answer question

0

I changed my approach, I instead set it up as checkboxes and limited the checkboxes this way

function NFTSelector() {
  var limit = 3;
$('#NFTGallery2 > li > input').on('change', function(evt) {
    if($('#NFTGallery2 > li > input:checked').length >= limit) {
        this.checked = false;
    }
});
}

almost 3 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error