2012-09-16 23 views
0

我想爲多個文本框的自動建議搜索框的基礎知識。我已經有一個腳本來添加/移動文本框,這是工作正常。但是我遇到的問題是能夠獲取頁面上的所有文本框,當按鍵完成時(基本onkeyup),它會提醒文本框的值。我能夠得到這個工作的文本框,我添加了我的自我在HTML中,但任何使用jQuery添加無法工作。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" /> 

回答

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>'); 
+0

,但由於某種原因它的工作這段時間。謝謝! – bs7280

1

嘗試使用,而不是onclick

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

這應該工作的動態添加元素通過delega灰。我加一個div包裝的元素,無論是手動和動態添加的,那麼你可以申請這個

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

看到這個working fiddle

+0

嘗試這樣做,永遠無法得到它使用的onkeyup曾是我前一陣子的第一件事就是到本地工作 – bs7280