crunch crunch - 7 months ago 11
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);
i++;
return false;
});


http://jsfiddle.net/crunchfactory/tZPg4/15947/

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

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 :)

HTML

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

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

Javascript

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

  $(removeBtn)
    .html("Remove")
    .addClass("btn-remove-input-wrapper");

  $(inputWrapper)
    .addClass('input-wrapper')
    .append(inputElement)
    .append(removeBtn);

  return inputWrapper;
}

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

  $(radioWrapper)
    .append(radioElement)
    .append(radioLabel);

  radioElement.type = 'radio';
  radioElement.name = '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() {
  $('#source').append(_createTextInput());
  $('#radio').append(_createRadioInput());
});

$(document).on('click', '.btn-remove-input-wrapper', function() {
  getRadioElement(this).remove();
  $(this).parent().remove();
});

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

DEMO