I am very new to Javascript, so sorry if I don't use the correct terminology.
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.
However I notice that all of the input fields have the same id (since the function makes the id the same each time).
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
startDate.className = 'startDate';
then use getElementsByClassName to retrieve them
var elements = document.getElementsByClassName ('startDate');// then loop through the elements
You should dynamically add the elements such that each element gets a new id. You could use a simple counter to append to your id names.
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
.
Hope that helps.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.