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>