0

複数のテキストボックスの自動提案検索ボックスの基本を作ろうとしています。テキストボックスを追加/削除するスクリプトが既にあり、正常に動作しています。しかし、私が抱えている問題は、ページ上のすべてのテキストボックスを取得できることです.キーが押されると(基本的にonkeyup)、テキストボックスの値が警告されます. HTMLで自分自身を追加したテキストボックスでこれを機能させることができましたが、jqueryを使用して追加されたものは機能しません。

ここにjqueryがあります:

    $(document).ready(function(){
    $counter = 0; // initialize 0 for limitting textboxes
    $('#buttonadd').click(function(){
        if ($counter < 10)
        {
            $counter++;
            $('#buttondiv').append('<div><label>Textbox #'+$counter+'</label><input type="text" name="textbox[]" class="textbox" value="" id="country"/></div>');
        }else{
            alert('You cannot add more than 10 textboxes');
        }
    });

    $('#buttonremove').click(function(){
        if ($counter){
            $counter--;
            $('#buttondiv .textbox:last').parent().remove(); // get the last textbox and parent for deleting the whole div
        }else{
            alert('No More textbox to remove');
        }
    });

    $('#buttonget').click(function(){
        alert($('.textbox').serialize()); // use serialize to get the value of textbox
    });

    $('input').bind('keyup', function() {
        alert($(this).val());
    });

    $('#dropdownadd').change(function(){
        $('#dropdowndiv').html(""); // when the dropdown change set the div to empty
        $loopcount = $(this).val(); // get the selected value
        for (var i = 1; i <= $loopcount; i++)
        {
            $('#dropdowndiv').append('<div><label>Textbox #'+i+'</label><input type="text" name="textbox2[]" class="textbox2" value="" /></div>');
        }
    });
});

ここにhtmlがあります:

<div id="buttondiv">
<!-- this is where textbox will appear -->
</div>
<div class="choices">
    <span>Adding Textbox using Button</span>
    <input type="button" id="buttonadd" value="Add Textbox"/>
    <input type="button" id="buttonremove" value="Remove Textbox"/>
    <input type="button" id="buttonget" value="Get Textbox" />
</div>

<input id="country" size="25" type="text" />
4

2 に答える 2

1

これは、テキストボックスが生成される前に keyup のバインド関数が呼び出されるために発生します。したがって、新しいテキストボックスを作成するたびに、バインディング コード (以下) を実行します。

$('input').bind('keyup', function() {
        alert($(this).val());
    });

またはより良い方法は、プレーンな JavaScript onkeyup 属性を使用して、定義した関数を呼び出すことです。例えば

$('#buttondiv').append('<div><label>Textbox #'+$counter+'</label><input type="text" name="textbox[]" class="textbox" onkeyup="function_abc(this);" value="" id="country"/></div>');
于 2012-09-16T19:37:25.033 に答える
1

onの代わりに を使用してみてくださいclick

http://api.jquery.com/on/

これは、委任を介して動的に追加された要素で機能するはずです。要素をラップするために div を追加し、手動と動的の両方で追加しました。これを適用できます

$('#container').on('keyup', 'input', function() {
    alert($(this).val());
});

この作業フィドルを参照してください

于 2012-09-16T19:28:43.770 に答える