0

The first input I can fill in the URL when clicking on an image.

When I add a new input and I click on the image, the URL appears on the button ADD not within the input with focus

https://jsfiddle.net/gislef/wyp4hzrd/

var input = '<label>Nome: <input type="text" name="images[]" /> <a href="#" class="remove">X</a></label></br>';

    $("input[name='add']").click(function( e ){
        $('#inputs_add').append( input );
    });

    $('#inputs_add').delegate('a','click',function( e ){
        e.preventDefault();
        $( this ).parent('label').remove();
    });


var focused = null;

$("input").on("focus", function() {
  focused = $(this);
})

$("img").click(function() {
  if (focused.length)
  focused.val($(this).attr("src"));
})

With fixed inputs I can work properly:

Fill inputs with urls images

Community
  • 1
  • 1
Gisele
  • 65
  • 7
  • Possible duplicate of [Event binding on dynamically created elements?](http://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements) – showdev Mar 09 '16 at 20:53

2 Answers2

1

please try with delegate, such as below:

var input = '<label>Nome: <input type="text" name="images[]" /> <a href="#" class="remove">X</a></label></br>';

    $("input[name='add']").click(function( e ){
        $('#inputs_add').append( input );
    });

    $('#inputs_add').delegate('a','click',function( e ){
        e.preventDefault();
        $( this ).parent('label').remove();
    });


var focused = null;

$(document).delegate("input", "focus", function() {
  focused = this;
  console.log(focused);
});

$("img").click(function() {
  if ($(focused).length)
  $(focused).val($(this).attr("src"));
});
AlanShearer
  • 141
  • 3
  • 2
    Note that "As of jQuery 1.7, [.delegate()](http://api.jquery.com/delegate/#entry-longdesc) has been superseded by the [.on()](http://api.jquery.com/on/) method." – showdev Mar 09 '16 at 20:58
1

It was not adding the link properly since you are creating dynamic controls

$("input").on("focus", function() {
  focused = $(this);
})

The above code was running and binding correctly to the first input inside your fieldset

You need to replace this code with a delegate on the parent fieldset that will contain the child input in order for dynamic controls to be registered.

$("fieldset").delegate("input", "focusin", function() {
  focused = $(this);
})

Here is a working fiddle with what I suppose is the intended behavior

https://jsfiddle.net/wyp4hzrd/1/