Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get values from dynamically added (using javascript) elements?

On my aspx page I dynamically create html controls on client side using javascript. For example, after page load you can click button in a browser, by clicking button html input and select elements appear. You may click once again, and this elements (input and select) will added again. So, you can create so many inputs and selects as you want (all this using javascript, no postbacks)

After user created some inputs and selects and entered some information in it, he posted form. I want on server side to find all this dynamically added elements and perform some actions depends on values in this controls.

How can I find dynamically added elements, and what is the best and elegant way to achieve this?

Thanks in advance.

like image 528
Kai Avatar asked Feb 23 '26 06:02

Kai


2 Answers

In the Javascript that creates the new elements, increment a counter each time an element is created. Add the value of the counter to the name of the input element so each element has a unique name.

Add the final value of the counter to a hidden form field when the form is posted.

In your server side code, create a loop that starts at zero and continues until you have reached the value of the counter. Within the loop, fetch the posted value of the corresponding form field.

like image 143
George Cummins Avatar answered Feb 25 '26 18:02

George Cummins


When you add the elements, assign unique IDs to them, and then retrieve their values using Request.Form["UniqueIdHere"] (C#) or Request.Form("UniqueIdHere") (VB.NET).

like image 43
Rick Liddle Avatar answered Feb 25 '26 18:02

Rick Liddle



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!