简体   繁体   English

以动态创建的形式命名输入元素

[英]Naming of input elements in a dynamically created form

I am very new to Javascript, so sorry if I don't use the correct terminology. 我是Java语言的新手,如果我使用的术语不正确,对不起。

I have a form that can dynamically grow. 我有可以动态成长的形式。 In other words I have buttons that will add labels and input fields to whenever the user clicks it. 换句话说,我有一些按钮,它们会在用户单击时向其添加标签和输入字段。

At the end of the form, I'd like to have some "done" button that runs another JavaScript function. 在表单的末尾,我想有一些“完成”按钮来运行另一个JavaScript函数。

However I notice that all of the input fields have the same id (since the function makes the id the same each time). 但是,我注意到所有输入字段都具有相同的ID(因为该函数每次都使ID相同)。

What is the correct way to access these variables??? 访问这些变量的正确方法是什么?

Below is the function to dynamically create the fields. 以下是动态创建字段的功能。 I havent written the function to use the form yet. 我还没有编写使用表格的功能。

function buildDefaultFields(){
    // Define container
    var chargeItem_container = document.getElementById("chargeItem_container");
    // INPUT Start Date
    chargeItem_container.appendChild(document.createTextNode('Start Date: '));
    var startDate = document.createElement("input");
    startDate.type = 'date';
    startDate.name = 'startDate';
    startDate.id = 'startDate';
    chargeItem_container.appendChild(startDate);
    chargeItem_container.appendChild(document.createElement("br"));

}

Don't use an id if its not going to uniquely identify a single element, instead use a class 如果ID不能唯一标识单个元素,请不要使用ID,而应使用类

startDate.className = 'startDate';

then use getElementsByClassName to retrieve them 然后使用getElementsByClassName检索它们

var elements = document.getElementsByClassName ('startDate');// then loop through the elements var elements = document.getElementsByClassName('startDate'); //然后遍历元素

You should dynamically add the elements such that each element gets a new id. 您应该动态添加元素,以便每个元素都有一个新的ID。 You could use a simple counter to append to your id names. 您可以使用一个简单的计数器来附加到您的ID名称。

For example, if you keep a global var count = 0 , then your first id could be 'startDate-' + count which will be startDate-0 , then perform an increment on count , so that the next time you add an element, it will get the id 'startDate-' + count = startDate-1 . 例如,如果您保持全局var count = 0 ,那么您的第一个id可能是'startDate-' + count ,它将是startDate-0 ,然后对count进行递增,以便下次添加元素时,它将获得'startDate-' + count = startDate-1

Hope that helps. 希望能有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM