How to get values from dynamically generated form elements

60 Views Asked by At

In canJs we use can-value to bind values of an element to controller.

//In controller
scope.attr("parameter") // It will give the value
//In mustache
<input type="text" can-value="parameter"/>

But how do we bind values of dynamically generated components to controller? I tried the following way

//In mustache
{{each arrayValues}}
<input type="text" can-value="parameter{{@index}}"/>
{{/each}}

but following is undefined

scope.attr("parameter1") 
1

There are 1 best solutions below

0
On

It's unclear which version of CanJS you're using. It looks like you're using mustache... which means you're using CanJS v2.x... which was deprecated a looong time ago - you should really upgrade.

Anyhow, what you want is to have a can.List of your items, and as you are iterating over that list, you reference the item in the list. It would look kind of like this:

scope.attr('parameters'); //-> ["foo", "bar"]

{{#each parameters}}
  <input type="text" can-value="{{.}}"/>
{{/each}}

If you are on v2.3 you should use {($value)} instead:

{{#each parameters}}
  <input type="text" {($value)}="{{.}}" />
{{/each}}

Please note that it has been years since I have used CanJS v2.x - so the above might not be 100% accurate, but it should get you close. The main point is you want to actually read the items from the array over which you are iterating.