2017-10-10 72 views
3

H我有一個按鈕「添加文本」,當它點擊時創建文本框,現在我怎樣才能得到JavaScript中的文本框的數量我創建文本框像如何在javascript中獲取文本框計數

<input type="text" name="my_textbox[1]" id="my_textbox1" /> 
<input type="text" name="my_textbox[2]" id="my_textbox2" /> 
<input type="text" name="my_textbox[3]" id="my_textbox3" /> 
<input type="text" name="my_textbox[4]" id="my_textbox4" /> 

爲什麼我需要算的,我是來自阿賈克斯獲取價值和創造新的文本框追加新的文本框狀的原因:

<input type="text" name="my_textbox[5]" id="my_textbox5" value="seomthing"/> 

現在我想知道存在的文本框的數量。如果我能通過JavaScript獲得計數,那將是最好的。

在此先感謝。

回答

1

使用document.querySelectorAll()獲取與id的子串匹配的所有元素(https://www.w3.org/TR/selectors/#attribute-substrings)。這個'[id^=「my_textbox」]'語法表示您選擇的所有元素都以"my_textbox"字符串開始,並且使用id。只需要查詢收集的length,你就完成了。請參閱以下片段:

var textboxCount = document.querySelectorAll('[id^="my_textbox"]').length; 
 
console.log(textboxCount);
<input type="text" name="my_textbox[1]" id="my_textbox1" /> 
 
<input type="text" name="my_textbox[2]" id="my_textbox2" /> 
 
<input type="text" name="my_textbox[3]" id="my_textbox3" /> 
 
<input type="text" name="my_textbox[4]" id="my_textbox4" />

4

給你輸入一個類名,以便您可以識別它們作爲一個羣體:

<input class="myInputs" type="text" name="my_textbox[1]" id="my_textbox1" /> 

然後,在JavaScript與querySelectorAll()選擇它們,並期待在返回集合的長度:

var inputs = document.querySelectorAll('.myInputs') 
var number_of_inputs = inputs.length 
相關問題