Maurius Maurius - 6 months ago 7
Javascript Question

.on() taking text input to produce another input label and form field

I'm trying to take input through a form, to produce another input field.

$(document).ready(function(){
$('.button').click(function(){
var value = $('#value').val();

$(document).on('click', '.button', function(){
$('#form1').append('<input type="text" id="value" value="' + value + '"><button class="button">Enter</button>');
});

return false;
});
});


This produces no error in Chrome console, though it errors in JSFiddle:

https://jsfiddle.net/yfjda40e/

What are the errors I am not catching?

Answer

Use Event delegation and e.preventDefault() to prevent default behavior of button

$(document).on('click', '.button', function(e) {
  e.preventDefault();
  var value = $('#value').val();
  $('#form1').append('<input type="text" id="value" value="' + value + '"><button class="button">Enter</button>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div id="content">
  <h1>Add field</h1>
  <form id='form1' action="" method='POST'>
    <input type="text" id="value" value="new value">
    <button class="button">Enter</button>
  </form>
</div>

<script src="http://code.jquery.com/jquery.min.js"></script>
<script src="js/app.js"></script>

Fiddle Demo