jquery动态添加文件字段

时间:2014-02-28 09:50:29

标签: php jquery html

你好我想做这样的事情: Here is example 我想点击“+”后添加2个索引名称为+ 1的新字段,点击“ - ”后我想删除这些字段。

2 个答案:

答案 0 :(得分:1)

试试这个

var i=1;
$('#pl').click(function(){ $(this).parents('.ch').prepend($('<input/>').attr({'type':'file','name':i,'id':i}));
    i++;
});
$('#mn').click(function(){
    $(this).parents('.ch').children('input').first().remove();
i--;
})

如果我理解你的问题可能有帮助

live demo

答案 1 :(得分:0)

试试 LIVE DEMO

<强> HTML

<div id="main_div">

  <div id="div_1">
    <div style="float:left">
        <label>Textbox 1 </label><input type="text" name="text1" id="text1">
    </div>
    <div style="float:left">
        <label>Textbox 2 </label><input type="text" name="text2" id="text2">
    </div>
    <div style="float:left">
        <label class="cursor_plus" onclick="add_Textbox();">+</label><label class="cursor_minus" onclick="remove_Textbox();">-</label>
    </div>
  </div>

</div>

JAVASCRIPT:

<script>
var counter = 1;
function add_Textbox()
{
    counter = counter + 1;
    var second = counter *2;
        var first = second - 1;
        var html = '<div id="div_'+counter+'" style="clear:both;">';
            html += '<div style="float:left">';
            html += '<label>Textbox '+first+' </label><input type="text" name="text'+first+'" id="text'+first+'">';
            html += '</div>';
            html += '<div style="float:left">';
            html += '<label>Textbox '+second+' </label><input type="text" name="text'+second+'" id="text'+second+'">';
            html += '</div>';
            html += '<div style="float:left">';
            html += '<label class="cursor_plus" onclick="add_Textbox();">+</label><label class="cursor_minus" onclick="remove_Textbox();">-</label>';
            html += '</div>';
            html += '</div>';
    document.getElementById('main_div').innerHTML += html;      
}

function remove_Textbox()
{
    if(counter==1)
    {
        alert("Cant' remove remaining One Only !!");
    }
    else
    {
        var id_rem = "div_"+counter+"";
        (elem=document.getElementById(id_rem)).parentNode.removeChild(elem)
        counter = counter - 1;  
    }   
}

</script>

CSS:

<style>
.cursor_plus{float:left; font-weight:bold; color:green; cursor:pointer}
.cursor_minus{float:left;margin-left:5px;font-weight:bold; color:red; font-size:12px; cursor:pointer}
</style>