0

I would like to add the value of an input field to the value of the attribute data-value. This actually works but I have a button that generates new fields. So the value can be added to the first input field but not to those which get generated by clicking the button.

<button id="another_field">Add a new field</button>

<div class="cpt_area">
  <input placeholder="Type something here..." class="full_width cpt_name" type="text" name="cpt_name[]">
</div>
// This will copy an input field
$('#another_field').click(function() {
  $('.cpt_name:first').clone().prependTo(".cpt_area").val('');
});

// This will generate a data-value attribute
$('input').keyup(function() {
  $(this).attr('data-value', $(this).val());
});

You can try it here: https://jsfiddle.net/e6ybk2d3/

Any ideas how I can fix this?

Álvaro González
  • 142,137
  • 41
  • 261
  • 360
Reza
  • 513
  • 3
  • 7
  • 20
  • Welcome to Stack Overflow. Questions are expected to be self contained, rather than just links to external resources, so they remain useful when links break. I've edited the question for you this time. – Álvaro González Jan 05 '17 at 10:23

2 Answers2

3

$('input') will only detect the inputs present when the page loads. The cloned ones won't be listening to the keyup event.

Instead of

$('input').keyup(function() {
  $(this).attr('data-value', $(this).val());
});

use

$('.cpt_area').on('keyup', 'input', function(ev){
  $(this).attr('data-value', $(this).val());
});
Boris K
  • 1,469
  • 9
  • 29
3

Use clone(true):

$('.cpt_name:first').clone(true)

event handlers won't be cloned if you don't set the argument withDataAndEvents as true, see the doc here: https://api.jquery.com/clone/

wong2
  • 34,358
  • 48
  • 134
  • 179