2015-05-29 50 views
0

請不要jQuery。如何創建一個輸入字段,然後預填充該字段

我已經看到了幾個例子,其中輸入字段已經存在於頁面上,然後再更新它,但我想動態創建輸入字段,然後用頁面中提供的信息填充它(因此current_value上面這個代碼段中定義變量):

for (i=0; i<tables.length; i++) { 
    (function(i) { 
    var sp = document.createElement('span'); 
    var act_table = document.createElement('table'); 
    act_table.id = 'act-tests-' + i; 
    act_table.style.display = 'none'; 

    var test_name_input = document.createElement('tr'); 
    test_name_input.innerHTML = '<tr><td width="100px">Name</td><td><input type="text" class="wideValue testName input"></td></tr>'; 
    test_name_input.setAttribute('value', current_rule); 

    act_table.innerHTML ='<tbody><tr>LOTS OF TABLE ROWS HERE</tr></tbody>'; 
    act_table.insertBefore(test_name_input,act_table.firstChild); 
    sp.appendChild(act_table); 
} 

該字段被示出,但不與我的current_value填充。

任何幫助非常感謝。

回答

3

在您的示例中,您將屬性設置爲tr,而不是創建的輸入字段。 嘗試這樣做:

document.getElementsByClassName("input")[you_index].setAttribute("value", current_value); 

下面的例子:http://jsfiddle.net/35g0ks0t/

+0

謝謝你,我會在幾個小時內嘗試了這一點的時候,我可以取回它。 – Ramy