Home > Software engineering >  Loop jQuery script for a list of elements
Loop jQuery script for a list of elements

Time:10-31

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:

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)

CodePudding user response:

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
};
  • Related