jamesinealing
jamesinealing

Reputation: 592

Setting the value of a form input in a Leaflet popup using jQuery

I have a draggable marker and want to update a form input with the new LatLng when the marker is moved.

On first load, the Popup html includes

<input type="text" id="newLatLng" name="newLatLng" value="">

The drag event is

marker.on('dragend', function(e) {
    console.log('dragend'); 
    newLatLng = marker.getLatLng().lat + ' ' + marker.getLatLng().lng;
    console.log(newLatLng);
    $('#newLatLng').val(newLatLng);
 });

The console log shows that the drag event and the correct values are being fetched, but the input value is not being set.

Any pointers welcome - I can't help feel I've missed something obvious!

Upvotes: 0

Views: 1416

Answers (1)

Regent
Regent

Reputation: 5178

Your code is executed before popup is recreated. To check this idea you can wrap your current $('input[name="newLatLng"]').val(newLatLng); with setTimeout with about 5 seconds delay and check the result. Full code:

setTimeout
(
    function()
    {
        $('input[name="newLatLng"]').val(newLatLng);
    }, 
    5000
);

Even though this code only for testing, you can use this idea to create workaround for problem by setting timeout for small period of time, checking for input existance, and if it hasn't existed yet, wait some more. Something like this:

(function check()
{
    if ($('input[name="newLatLng"]').length)
    {
        $('input[name="newLatLng"]').val(newLatLng);
        ... other related logic
    }
    else
    {
        setTimeout(check, 200);
    }
})();

Upvotes: 1

Related Questions