kash101
kash101

Reputation: 269

write to dynamically created div from dynamically created input

how can i update the contents of a dynamically created div as i type into an input field that was also created dynamically.

First i have an input that requests the number of code blocks i want:

$("#count-trigger").click(function(){
    var count = $("#slide-count").val();
    if (count !== "" && $.isNumeric(count)) {
        var i = 1;
        while (i <= count) {
            $('.appendHere').append(

 // Div I want to write to.
 '<div 'id="slide-content_'+i+'">'Sample Title </div>'+

 // Input field used to populate above div
 ' <input                                            '+ 
 '   type    = "text"                                '+
 '   name    = "slide_name_'+i+'"                    '+
 '   data-target    = "slide_name_'+i+'"             '+
            ));
            i++;
        }
});

The above is pretty obvious, enter in a value press go and i get x number of divs/inputs.

Problem comes when trying to populate a created div as I type into created input.

Any help would be greatly appreciated.

Upvotes: 0

Views: 67

Answers (2)

sabithpocker
sabithpocker

Reputation: 15558

You can use an IIFE to keep a scope for each iteration and use variables that are consumed later. In latest ECMA, you can even make use of block level scope for the same.

$("#count-trigger").click(function() {
  var count = $("#slide-count").val();
  var i = 1;
  while (i <= count) {
    (function() {
      var codeOutput, codeInput;
      codeOutput = $('<div class="code">');
      codeInput = $('<input type="text"/>');
      codeInput.on('input', function() {
        codeOutput.text($(this).val())
      })
      $('.appendHere').append(codeInput, codeOutput);
    })();
    i++;
  }
});
.code {
  border: 1px dashed #bc0000;
  min-height: 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input id="slide-count" type="number" />
<button id="count-trigger">Create</button>

<div class="appendHere"></div>

Upvotes: 1

kash101
kash101

Reputation: 269

Okay, so the change suggested from @zak did the trick.

I added a onchange="liveUpdate(input_id)" to each input.

and then add this function

function liveUpdate(e_id) {
    var typed = $('#'+e_id).val();
    $('[data-target='+e_id+']').text(typed);
}

I imagine there is a better solution to this but considering how much I suck at js and the fact that it works perfectly --I am happy with.

Upvotes: 0

Related Questions