0

i have script like this, for append a new elment based user input

var tmp;
$('#add').click(function(){

            var galer=parseInt($('#many').val());

                for(var h=1;h<=tmp;h++){
                    $(".af_"+h).remove();                       
                }

                for(var x=1;x<=galer;x++){
                    $("#kontenPlus").append("<input type='file' id='photo_"+x+"'> <input type='text' id='src_"+x+"'>");

                }

                tmp=galer;                  

       });

for(var u=1;u<=tmp;u++){            
    $('#photo_'+u).change(function(){
            $('#src_'+x).val($(this).val());
    });
}

this html code:

<input type='text' id='many'><div id='add'>Add element</div>
<div id='kontenPlus'></div>

i want to ask why value of '#photo_+x', isn't put in '#src_'+x, is function can be looped ?

LINK:http://jsfiddle.net/rizalfarez/V5AdP/3/

Mamen
  • 1,322
  • 5
  • 21
  • 44

2 Answers2

0

Because these elements are being dynamically created you will need to delegate the event listening like

$(window).on( "change", function() {
    // 
    var id = $(this).id;
    //
    if (id.indexOf("photo") === 0) {
Scary Wombat
  • 44,617
  • 6
  • 35
  • 64
0

the reason that the value of text boxes does not get updated is because they are dynamically created, so the change event is not bind to them.

I have changed your code and optimized it a little like this:

var tmp;
$('#add').click(function(){
    var galer = parseInt($('#many').val());

    $('.af').remove();                       

    for(var x=1;x<=galer;x++)
        $('#kontenPlus').append('<div class="af"><input type="file" id="photo_'+x+'"><input type="text" id="src_'+x+'"></div>');

    $('[id^="photo_"]').each(function(){
        $(this).change(function(){
            $(this).next().val($(this).val());
        });
    });
});
EhsanT
  • 2,077
  • 3
  • 27
  • 31