Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

268
Views
Loop jQuery script for a list of elements

I have the following jQuery script that I need to execute for a long list of objects.

$("#ID_001").change(function(event) {
    event.preventDefault();
    if(map.hasLayer(ID_001)) {
        $(this).removeClass('selected');
        map.removeLayer(ID_001);
    } else {
        map.addLayer(ID_001);
        $(this).addClass('selected');
   }
});

What I have done

Using the following resource:

  • api.jquery.com
  • jquery-loop-for-script
  • jquery-for-each-looping-a-list-of-objects

I don't think this is a duplicate question of the above as this include an event handler function.

I have written the following loop but this still doesn't work. I can't understand where is the problem.

var obj = {
    "#ID_001": "ID_001",
    "#ID_002": "ID_001"
  };

  $.each( obj, function( key, value ) {
    $(key).change(function(event) {
        event.preventDefault();
        if(map.hasLayer(value)) {
            $(this).removeClass('selected');
            map.removeLayer(value);
        } else {
            map.addLayer(value);
            $(this).addClass('selected');
       }
    });
  });

Can anyone explain to me where is the problem?

Further details

The script is a part of LeafLet map control buttons. Chrome DevTool show this message of error when I click on #ID_001 element, so I think that the problem is that value variable doesn't get the proper value.

Uncaught TypeError: Cannot create property '_leaflet_id' on string 'L_puntiA' at m (Util.js:56) at i.hasLayer (Layer.js:211) at HTMLInputElement. (mymap_main.js:103) at HTMLInputElement.dispatch (jquery-3.3.1.slim.min.js:2) at HTMLInputElement.v.handle (jquery-3.3.1.slim.min.js:2)

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

As sorted out in the comment your problem is that you define the objects with strings instead of variables.

Instead of:

var obj = {
  "#ID_001": "ID_001",
  "#ID_002": "ID_001"
};

Use:

var obj = {
  "#ID_001": ID_001,
  "#ID_002": ID_002
};
about 4 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 Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!