17

I use VueJs, i need to extract javascript variable to generate hidden fields.

But i need to set the name by the index of the variable.

I want to use zig-zag naming schema.

like,

 <input type="text" name="segment[{index}][field_name]" :value="{value}">

Javascript Variable:

    var test_template = {
                        0: {
                            nb: 2
                        },
                        1: {
                            nb: 1
                        },
                        2: {
                            nb: 4
                        }
                    };

Foreach with Variable to Generate Hidden Fields :

    <div v-for="(a,index) in test_template" class="row">            
      <input type="hidden" :name="segment[index][nb]" :value="a.nb">
   </div>

Here, :name is a dynamic instance for access vuejs values. index is vuejs variable but "segment" is not a vuejs variable, its actually a string.

But i need this schema to generate array of inputs.

Is this possible ?

Or Any other solutions are there ?

Thanks in Advance !

1
  • Have you tried segment + a.nb ? Commented Dec 10, 2016 at 0:01

2 Answers 2

47

To create input elements with dynamic names by index, you can use the + in a JS expression to concatenate:

<div v-for="(a,index) in test_template" class="row">            
  <input type="hidden" :name="'segment[' + index + '][nb]'" :value="a.nb">
</div>

Generates:

<input type="hidden" name="section[0][nb]" value="2">
<input type="hidden" name="section[1][nb]" value="1">
<input type="hidden" name="section[2][nb]" value="4">

See: https://v2.vuejs.org/v2/guide/syntax.html#Using-JavaScript-Expressions

Sign up to request clarification or add additional context in comments.

1 Comment

You can also use JS6 interpolation. :name="`segment[${index}][nb]`"
15

I ran across the same problem as you, and here is how i fixed it !

make a method like this in your vue-instance

getInputName(index, dataName){
      return "items["+index+"]["+dataName+"]";
    }    

then you can use it like this:

<input v-bind:name="getInputName(index, 'name')" type="text" v-model="item.name">
<input v-bind:name="getInputName(index, 'price')" type="text" v-model="item.price">

which will give you this post result:

"items" =>[
    0 =>[
      "name" => "test"
      "price" => "23"
    ],
    1 =>[
      "name" => "jakke"
      "price" => "99,2312"
    ]
]

And thats it...

Cheers, Sipman

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.