removing dynamically created <div> triggered from Google map marker click

From the digging I've done it looks like I want to use .on but I'm note sure how to go about implementing it. I'm still learning javascript and jquery so I could be missing something...

The code below runs when a marker is added to a Google map (v3 api). It creates a marker and adds a form field. If the user then clicks on the newly created marker the marker is hidden and the code should then remove the form as well. The marker removes fine but I can't get the removed. This is the line I'm looking for help with:

    $('#newdiv + site_count).remove(); 

If i manually replace newdiv+ site_count with a valid number (say 6 so newdiv6) the code works I just can't figure out how to reference it live... Finally here is the rest of the relevant code:

google.maps.event.addListener(map, "click", function(event) {
    marker = new google.maps.Marker({
      position: event.latLng,
      map: map
    newlocation = "<div id='newdiv" + site_count + "'><input type='text' size='3' name='loc[" + site_count + "]' id='newid" + site_count + "' value = '0' /></div>";
    google.maps.event.addListener(marker, "click", function(event) {
                $('#new+ site_count).remove(); 


Thanks for taking the time to have a look at my issue. --AJ



This line

$('#new+ site_count).remove();

has three issues:

  1. There's no closing ', so it causes a syntax error.

  2. You're giving the div containing the form fields the ID newsiteX, but that line is trying to find it using the ID newX instead.

  3. After creating your new div, you're incrementing site_count, but later you're trying to find the div using the new value of site_count, and so you won't. That is, if site_count is 0 and you create a new div, it'll have the id "newsite0" and site_count will get incremented to 1. Then when you go to remove it on click, even if you fix the items above, you'll be looking for newsite1 rather than newsite0.

You haven't shown enough of your code for me to confidently correct it for you, but probably something along these lines:

$('#newsite' + (site_count - 1)).remove();

That said, you may want to step back and take a deeper look at the structure, this seems a bit fragile (but may be fine).


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.