首页 文章

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

提问于
浏览
0

我正在构建一个调查,我需要能够在另一个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中创建一个对象 .

谢谢!

2 回答

  • 0

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

    我想这就是你的意思:)

    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

  • 1

    因为live已被弃用,我会使用以下格式:

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

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

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

    上面的代码需要针对正确的div进行更新,但是它会获得每个输入字段的类型,并将其放入div的HTML中 .

相关问题