2

我在使用 JavaScript 或 jQuery创建具有字符串计数的动态字段时遇到问题。

简报

我想在 sting count 的帮助下创建动态字段,例如,当我player textfield像这样写一些文本时,p1,p2,p3它们会创建三个file fieldsdynamicDiv或者当我同时删除player textfield这样p1,p2的一些文本时,它们只会创建两个file fields

整个场景取决于keyup event

代码:

<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
function commasperatedCount(){
    var cs_count = $('#player').val();
    var fields = cs_count.split(/,/);
    var fieldsCount = fields.length;

    for(var i=1;i<=fieldsCount;i++){
        var element = document.createElement("input");
        element.setAttribute("type", 'file');
        element.setAttribute("value", '');
        element.setAttribute("name", 'file_'+i);

        var foo = document.getElementById("dynamicDiv");
        foo.appendChild(element);
    }
}
</script>

<form>
<label>CountPlayerData</label>
<input type="text" name="player" id="player" onkeyup="return commasperatedCount();" autocomplete="off" />
<div id="dynamicDiv"></div>

<input type="submit" />
</form>
4

2 回答 2

1
var seed = false,
    c = 0,
    deleted = false;
$('#player').on('keyup', function(e) {
    var val = this.value;
    if ($.trim(this.value)) {
        if (e.which == 188) {
            seed = false;
        }
        if (e.which == 8 || e.which == 46) {
            var commaCount = val.split(/,/g).length - 1;
            if (commaCount < c - 1) {
                deleted = true;
            }

        }
        commasperatedCount();
    } else {
        c = 0;
        deleted = false;
        seed = false;
        $('#dynamicDiv').empty();
    }
});

function commasperatedCount() {
    if (deleted) {
        $('#dynamicDiv input:last').remove();
        deleted = false;
        c--;
        return false;
    }
    if (!seed) {
        c++;
        var fields = '<input value="" type="file" name="file_' + c + '">';
        $('#dynamicDiv').append(fields);
        seed = true;
    }
}​

演示

于 2012-06-04T08:57:38.147 回答
1
<script>
    function create(playerList) {
        try {
            var player = playerList.split(/,/);
        } catch(err) {
            //
            return false;
        }
        var str    = "";

        for(var i=0; i<player.length; i++) {
            str += '<input type="file" id="player-' + i + '" name="players[]" />'; 
            //you wont need id unless you are thinking of javascript validations here
        }

        if(playerList=="") {str="";} // just in case text field is empty ...

        document.getElementById("dynamicDiv").innerHTML = str;
    }
</script>

<input id="playerList" onKeyUp="create(this.value);" /><!-- change event can also be used here -->

<form>
    <div id="dynamicDiv"></div>
</form>
于 2012-06-04T20:58:28.253 回答