crunch crunch - 1 year ago 98
Javascript Question

Add/Remove Input Fields Dynamically and preview field values in separate div

I'm building a survey and I need the ability to preview dynamic input fields as they are created, in another div.

For example, here I'm creating text inputs (pretty trivial) and creating radio buttons in a separate div:

$('#p_scnt, #p_scnt_' + i +'').live('click', function() {
$('<p><label for="p_scnts"><input type="text" size="20" id="p_scnt_' + i +'" value="" placeholder="Input Value" /></label> <a href="#" id="removeObject">Remove</a></p>').appendTo(scntDiv);
$('<p><input type="radio" value="' + crunchValue + '">' + crunchValue + '</p>').appendTo(crunchville);
return false;

I'm not sure how to get the values, hence the obviously 'undefined'.

Three things:

I want to get the values from the text boxes as they are typed to the values in the separate div.

I want to click in the text box to create a new text box, which, a) only seems to work in the top 2, and b) if a box has a null value, don't create an object in the other div.

Thank you!

Answer Source

I want to get the values from the text boxes as they are typed to the values in the separate div.

I think this is what you mean :)


<button id="btn-add">Add</button>

<div id="source"></div>
<div id="preview"></div>


// --- Main functions --- //
function _createTextInput() {
  var inputWrapper = document.createElement('div');
  var inputElement = document.createElement('input');
  var removeBtn    = document.createElement('button');



  return inputWrapper;

function _createRadioInput() {
  var radioWrapper = document.createElement('div');
  var radioElement = document.createElement('input');
  var radioLabel   = document.createElement('label');


  radioElement.type = 'radio'; = 'group';
  return radioWrapper;

// --- Helper functions --- //

function getIndex(me) {
  return $(me).parent().index();

function getRadioElement(me) {
  return $('#radio div:nth-child(' + (getIndex(me) + 1) + ')');

// --- Event handlers --- //

$('#btn-add').click(function() {

$(document).on('click', '.btn-remove-input-wrapper', function() {

$(document).on('keyup', '.input-wrapper input', function() {
  var index = getIndex(this);
  var inputText = $(this).val();


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download