-1

I have a page where users can add their scripts to a form and then submit them. I'm using .append() to allow users to add new scripts if required, however when a new script is added the character count for that script no longer works, even though the HTML is identical (besides IDs). Is there a way to update the DOM so it will also recognise these new divs?

Here is an exmaple:

var $scriptNumber = 2;
$('.script').keyup(charCount);
$('#new-script').click(addScript);

function charCount() {
 var $chars = $(this).val().length;
 $(this).siblings('.char-count').html($chars + ' Characters');
}

function addScript() {
 $('#scripts').append('<div id="script-' + $scriptNumber + '-wrap" class="script-wrap"><label for="script-1">Script ' + $scriptNumber + '</label><textarea id="script-' + $scriptNumber + '" class="script" cols="40" rows="3"></textarea><span class="char-count">0 Characters</span></div>');
  $scriptNumber++;
}
#scripts {
  padding: 12px;
}
.script-wrap {
  margin-bottom: 12px;
}
label {
  font-weight: bold;
}
textarea {
  width: 100%;
}
#new-script {
  margin-left: 12px;
  padding: 4px 12px;
  background: purple;
  color: white;
  cursor: pointer;
}
#new-script:hover {
  background: blue;
}
<div id="scripts">
  <div id="script-1-wrap" class="script-wrap">
    <label for="script-1">Script 1</label>
    <textarea id="script-1" class="script" cols="40" rows="3"></textarea>
    <span class="char-count">0 Characters</span>
  </div>
</div>
<span id="new-script">New Script</span>

1 Answers1

1

Change the line $('.script').keyup(charCount); to $(document).on('keyup', '.script', charCount);.

The issue is being caused because it's a dynamically created element. Because of this we need to attach the function to something present on the page at the time of loading.

Here's a working JS Fiddle example