繁体   English   中英

动态添加/删除输入字段并在单独的div中预览字段值

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

我正在构建调查,并且需要能够在另一个div中预览动态输入字段的创建过程。

例如,在这里我要创建文本输入(非常简单)并在单独的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/

我不确定如何获取值,因此显然是“未定义”。

三件事:

我想从文本框中获取值,因为它们被键入到单独的div中的值。

我想在文本框中单击以创建一个新文本框,a)似乎只在顶部2起作用,b)如果一个框具有空值,则不要在另一个div中创建对象。

谢谢!

我想从文本框中获取值,因为它们被键入到单独的div中的值。

我想这就是你的意思:)

的HTML

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

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

Java脚本

// --- 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);
});

演示

由于不推荐使用live,因此我将使用以下格式:

$(document).on("click",'#p_scnt, #p_scnt_' + i,function(){
//
});

然后给每个输入一个文本输入类(或其他)

$(document).on("keyup",".text-input",function(){
   $("div").html($(this).val());
});

上面的代码将需要针对适当的div进行更新,但是它将获取类型作为每个输入字段的类型并将其放入div的HTML中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM