2

JavaScript または jQuery を使用して文字列カウントを持つ動的フィールドを作成する際に問題があります。

ブリーフィング

文字列カウントを使用して動的フィールドを作成しplayer textfieldたい.p1,p2,p3file fieldsdynamicDivplayer textfieldp1,p2file 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
<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 に答える
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 に答える