Guide on building a Vue Js input name field with string-variable schema

I have a project using VueJs and I am looking to extract JavaScript variables to create hidden fields.

My goal is to set the name of the field based on the index of the variable, following a zig-zag naming schema.

For example:

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

The JavaScript Variable:

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

Foreach Loop for Generating Hidden Fields with Variables :

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

In this code snippet, :name dynamically accesses VueJS values. index is a VueJS variable, but "segment" is not - it's actually a string.

However, I need this structure to generate an array of inputs.

Is there a way to achieve this?

Or are there any alternative solutions available?

Thank you in advance!

Answer №1

If you want to dynamically create input elements with unique names based on an index, you can utilize the + operator in a JavaScript expression for concatenation:

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

This will result in the following HTML output:

<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">

Check out more details at: https://v2.vuejs.org/v2/guide/syntax.html#Using-JavaScript-Expressions

Answer №2

Encountered the same issue but found a solution!

Here's a method you can use within your Vue instance:

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

Then, implement 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">

This will result in:

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

That's all for now.

Cheers, Sipman

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible to transition my Vue.js web application to NativeScript-Vue?

Hello, I have a quick question for you. I currently have a web project developed in Vuejs and I am wondering if there is a way to convert it or mirror it to NativeScript-Vue somehow. Thank you and warm regards! ...

Error in Node Express server: Status code 0 is not valid

As a beginner node.js/js programmer, I am encountering an error code while trying to make a POST request on my application. The error message reads as follows: Error: [20:22:28] [nodemon] starting `node app.js` Running server on 3000 Mon, 27 Jun 2016 19:2 ...

The inner workings of Virtual DOM in React and Vue disclosed

I am a student experimenting with creating my own Virtual DOM for a college project in JavaScript, keeping it simple without advanced features like props or events found in popular frameworks like React and Vue. I'm curious about code splitting. If I ...

Unlock the potential of Stripe's confirmCardSetup method when working with multiple elements in Laravel Cashier integrated with a Vue application. Master

Is it possible to send inputs separately from Stripe using the confirmCardSetup method, even though the documentation only mentions one cardElement element? https://stripe.com/docs/js/setup_intents/confirm_card_setup -> check the official documentation ...

How can I modify the appearance of a slider's range?

I'm struggling with customizing the style of a price slider input range. No matter what I do, the changes don't seem to take effect. Can anyone pinpoint where I may be going wrong? Appreciate any guidance on this! Thank you! <div class=" ...

What's the best way to include various type dependencies in a TypeScript project?

Is there a more efficient way to add types for all dependencies in my project without having to do it manually for each one? Perhaps there is a tool or binary I can use to install all types at once based on the dependencies listed in package.json file. I ...

Tips on expanding the row number column width in jqGrid

Within my JQuery Grid, I am utilizing a parameter called rownumbers. jQuery("#dateInfo").jqGrid({ url : theURL, datatype : "json", sortable: false, colNames:['Date & Time'], colModel:[{name:'arrivalTime',index:'arrivalTime& ...

Creating a basic jQuery button to switch an element's background color is a breeze

I'm new to this, so I hope this is a straightforward question. I'd like to use the bgtoggle class as a button to switch the background color of the metro class. I know I'm doing something wrong because it's not working as expected. Any ...

Exploring the world of Django and JSON POSTs in the realm of Google API mania

Project Overview I am currently developing an application aimed at assisting users in finding rides. My tech stack includes Django, Python 2.7, and integration with Google Maps and Directions APIs. Within a specific view, I present a map where users can ...

Is it possible to replace JavaScript files that are included in my index page if I am utilizing conditional comments specifically for IE9?

My website works perfectly in all browsers, except for IE9. After some investigation, I discovered that the issue lies with a jQuery plugin called multilevelpush.js. While it works great on other browsers, it simply won't cooperate with IE9. Upon fur ...

Eliminate unnecessary scrollbar from fancybox iframe

I am trying to display content in an iframe using Fancybox, but I am encountering an issue. Despite all the content being contained within the iframe, horizontal and vertical scroll bars are appearing. When inspecting the element in Firefox, I noticed th ...

Obtaining the image with PHP

As a newcomer to PHP and Ajax queries, I am trying to utilize the croppie.js plugin to upload a profile image. However, when I upload the image, it is saved as 1580192100.png. The problem arises when attempting to later retrieve the image based on the user ...

Animating range tick movements as the range thumb moves

My custom range input includes a span that displays the range's value and a div with multiple p elements acting as ticks. To create these ticks, I had to use a custom div because using "appearance: none" on the range hides the ticks by default. The ti ...

Is it possible to utilize global variables within CSS properties?

I have a scenario where I need to dynamically change values in an animation. The line of code that needs modification is: clip-path: polygon(var(clip1) 0, 100% 1%, 100% 100%, 50% 100%); let root = document.documentElement; root.style.setProperty('c ...

What could be the reason for the "category empty" message appearing at the first index after clicking on the add

When I click on the add products button, why is the category name empty at the first index? 1. The text starts from index 2 of the category column. 2. When I change the value from the dropdown, it first displays the previous value in the category column an ...

Is it possible to configure modules in Nuxt3 without the use of the createApp() function by utilizing the

Is there a Vue function available that can achieve the same effect as app.use(UseWagmiPlugin, config); in the code snippet below, without having to import './app.vue' and use createApp()? (For more information, refer to the documentation on GitHu ...

Tips for customizing the appearance of a single plot within a time series chart using FusionCharts or FusionTime

I've implemented a time series line graph using FusionCharts in the following code snippet: const MyChart = () => { const schema = [ { name: "Category", type: "string" }, { ...

Utilizing a Single Background Image Across Several Div Elements

Let me illustrate my question using a sequence of images. The div container is set to display the background image as follows: In addition, there will be tile-shaped divs layered on top of the image: I aim to have the background image visible only withi ...

An Illustration of Basic Nested Controller within Directive Parameters

Check out this code snippet app.directive('hello', function() { return { restrict: "E", templateUrl: "/Angular/Modules/Selector.html", controller: function () { this.message = [enter the attribute message he ...

The HTML5 video will continue playing indefinitely as long as its readyState remains at 4

In my efforts to develop a personalized HTML5 video player that can handle live streaming, recording of live streams, and playing regular video files, I have run into an issue with creating a custom seeking bar. To achieve this, I implemented the following ...