访问使用jQuery或纯的Javascript HTML输入文本框的数组
我在找创建一个包含输入文本框,一个动态的数字形式。我想每一个文本框,形成一个阵列的一部分(这在理论上使我更容易循环通过他们,特别是我不知道最终会存在的文本字段数)。该HTML code想是这样的:
I'm looking to create a form which contains a dynamic number of input text boxes. I would like each text box to form part of an array (this would in theory make it easier for me to loop through them, especially as I won't know the number of text fields that will eventually exist). The HTML code would like something like:
<p>Field 1: <input type="text" name="field[1]" id="field[1]"></p>
<p>Field 2: <input type="text" name="field[2]" id="field[2]"></p>
<p>Field 3: <input type="text" name="field[3]" id="field[3]"></p>
<p>Field 4: <input type="text" name="field[4]" id="field[4]"></p>
<p>Field 5: <input type="text" name="field[5]" id="field[5]"></p>
此数据随后将被发送到一个PHP脚本,并会被重新presented作为数组 - 或者至少,这是理论
This data would then be sent to a PHP script and would be represented as an array - or at least, that's the theory.
所以我的第一个问题是,这是可以实现使用HTML?被设计形式上班呀?
So my first question is, is this achievable using HTML? Are forms designed to work that way?
如果这个问题的答案是是,我将如何然后去有关访问每个使用jQuery或没有这些的,老式的JavaScript?
If the answer to that is "yes", how would I then go about accessing each of those using jQuery or failing that, plain old JavaScript?
我已经尝试实现这一目标使用以下的jQuery code:
I've attempted to achieve this using the following jQuery code:
someval = $('#field[1]').val();
和
someval = $('#field')[1].val();
和下面的JavaScript:
and the following JavaScript:
someval = document.getElementById('related_link_url')[1].value;
不过,我已经没有任何运气。
But I've not had any luck.
先谢谢了。
编辑:
我要指出,但从一个Javascript一点,我已经受够了工作,其中每个元素的ID是一样的东西field_1,field_2等。不过,我觉得,如果我可以通过将每个文本框为实现这一目标一个数组,它会做出整洁,更易于管理code。
I should note that from a Javascript point of view, I've had it working where the ID of each element is something like field_1, field_2 etc. However, I feel that if I can achieve it by placing each text box into an array, it would make for tidier and easier to manage code.
首先, ID
属性不能包含 [
或]
字符。
First of all, id
attribute cannot contains [
or ]
character.
有是很多的方式来获得的jQuery /这些元素普通的JavaScript引用。您可以使用后代选择:
There is lots of ways to get jQuery/plain JavaScript references to these elements. You can use descendant selector:
<fieldset id="list-of-fields">
<!-- your inputs here -->
</fieldset>
$("#list-of-fields input");
document.getElementById("list....").getElementsByTagName("input");
您也可以使用属性选择:
You can also use attribute selector:
$("input[name^=field]");
我不知道这是否是唯一的办法,但我认为,在普通的JavaScript你必须获取所有输入
元素(文件。的getElementsByTagName
),然后遍历这些元素的数组,并检查每个元素(是否有其价值与启动
)。名称
属性字段
I'm not sure whether that's the only way but I think in plain JavaScript you'll have to fetch all input
elements (document.getElementsByTagName
) and then loop through array of these elements and check each element (whether it has name
attribute which value starts with field
).