简体   繁体   中英

How to make js generated elements interact properly with static html elements?

Js student here.

I have made an example CODEPEN .

In this test case,as you can see in the above code on the right side i have 6 hardcoded html inputs,3 for first name and 3 for last name. On the left side i have a <button> which is called ADD ,and with every click of this button (with a maximum of 3 clicks) the function addInputs() generates a <li> element inside <ol id="originContainer"></ol> .

This generated <li> element contains 2 html inputs,one for the first name and one for the last name,every generated input gets a unique id using a counter variable ( var inputscounter=0; ).

The goal is to copy dynamically,whatever i type in the generated inputs -to the left- to the hardcoded ones -to the right-,first name to first name,last name to last name,all that by using the function changeValues() which runs with every keyup of the generated inputs.

My problem is ,the function changeValues() works fine but only after i generate all 3 of the elements ( As its visualized in THIS picture ) on the left,but not with just one of them,or 2 ( like THIS )

What am i missing?

When you try to get the value of an element that is not created yet, the function throws an error. That is, in your changeValue function where you try to get the value attribute on FnameX when it is undefined (since it can't find the element in the DOM). Same for adding the click handlers on undefined elements.

You could fix that by either checking if Fname1 etc are defined before you try to get their value.

A nicer approach would be to store in an array which elements you have generated so far. Then loop over those elements and transfer its values.

You can either store an array of ids you can use to find an element when you don't need to access them that often. In this case I would store the objects themselves.

Also you don't have to add click handlers on every element, every time you add one.

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.

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