Ways to loop through HTML elements based on certain criteria?

Issue : The v-for loop is successfully iterating and binding data in the HTML template, but there is a challenge in partially iterating it based on certain conditions. Please refer to the JSFiddle link below for a demo.

Objective : In the provided demo link, for the "Second Section", the requirement is to display the input textbox only once, vertically aligned center (in front of beta), instead of repeating it multiple times. Other values like alpha, beta, gama can be repeated.

JSFiddle Link

var arr = [{
    sectionName: 'First Section',
  data: ['alpha', 'beta']
}, {
    sectionName: 'Second Section',
  data: ['alpha', 'beta', 'gama']
}];

var myitem = new Vue({
  el: '#my-items',
  data: {
    items: arr
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.6/vue.js"></script>

<div id="my-items">
  <div v-for="item in items">
    {{ item.sectionName }} <hr>
    <div v-for="sectionData in item.data" style="margin: 5px">
      <span style="width:50px;text-align:left;display:inline-block;">{{ sectionData }}</span> <input type="textbox"/>
    </div>
  </div>
</div>

https://i.sstatic.net/G5wvU.png

Answer №1

To utilize index in your v-for loop, you can incorporate it into conditional statements within the iteration. I have adjusted your example to demonstrate this concept. The text box will display for each section during the initial loop or when sectionData is equal to 'beta'. This condition is specified within the v-if statement.

While this method works, it is recommended to create a component whenever employing v-for loops. Otherwise, the structure can become convoluted and challenging to comprehend.

var items = [{
    name: 'First Item',
  data: ['alpha', 'beta']
}, {
    name: 'Second Item',
  data: ['alpha', 'beta', 'gama']
}];

var myVueItem = new Vue({
  el: '#my-vue-items',
  data: {
    items: items
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.6/vue.js"></script>

<div id="my-vue-items">
  <div v-for="(item, index) in items">
    {{ item.name }} <hr>
    <div v-for="sectionData in item.data" style="margin: 5px">
      <span style="width:50px;text-align:left;display:inline-block;">{{ sectionData }}</span>
      <input 
        v-if="index === 0 || sectionData === 'beta'"
        type="textbox"
      />
    </div>
  </div>
</div>

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

The 'newPassword' must be included as a String parameter

SOLVED The issue has been resolved. It was found that the backend required data in param format, so the form sent by Vue was changed to param instead of data! I am currently working on a password change page. I encountered an error stating that there was ...

Putting together Modular Client-side JavaScript

Is there a way in Node.js to dynamically "require()" javascript files similar to PHP's require function? It would be great to use this feature in my client-side code for development purposes without actually calling a specific javascript function. Rat ...

Integrating PHP code into a React.js application can provide

I am currently integrating react.js into a section of my app and exploring the possibility of embedding some PHP code into react.js. This would allow me to avoid having to completely rewrite the backend that was originally written in PHP. Here's an ex ...

The SMTP request for a one.com domain email is experiencing issues when sent from the render.com server

I have set up an Express JS server on render.com to handle SMTP calls to an email service hosted on one.com with a custom domain. Utilizing nodemailer to manage the SMTP call: app.post("/send-mail", validate(schema), (req, res) => { console. ...

The button fails to log any text to the developer console

Attempting to verify the functionality of my button by logging a message on the developer console. However, upon clicking the button, the text does not appear in the console. import { Component, EventEmitter, Input, Output } from '@angular/core'; ...

Why are the HTML links generated by JS not opening in Chrome?

<a href='http://www.xyz.hu/xyz' alt='Kosár' title='Kosár'>Megtekintés</a> Additionally: - A setInterval function refreshes the sibling's content every second, although it should not affect this specific el ...

Explore the feature of toggling visibility of components in Vue.js 3

I am facing an issue with showing/hiding my sidebar using a button in the navbar component. I have a navbar and a side bar as two separate components. Unfortunately, none of the methods I tried such as v-show, v-if, or using a localStorage value seem to wo ...

The Lerna command for adding packages fails with an error message stating that the packages are not related

Currently, I am utilizing lerna to manage a multirepo containing interrelated packages. This issue only arose after installing a new operating system. Whenever I attempt to utilize lerna add to add a dependency from one package to another, an error occurs ...

Violation of content security policy due to the usage of inline styling in the tawk.to

I have incorporated Tawk.to's chat widget codes into my website to include the chat bubble. The code is placed within a JS file: var Tawk_API = Tawk_API || {}, Tawk_LoadStart = new Date(); (function() { var s1 = document.createElement("script&qu ...

An issue occurred while attempting to read words from JSON file

My current issue involves loading words from JSON into my webpage. The images are functioning properly, thankfully. I have already successfully loaded the necessary images through JSON onto my webpage. However, I am still in need of loading words through ...

Material UI filterSelectedOptions not functioning properly on initial search with multiple autocomplete

When I utilize the filterSelectedOptions prop in my autocomplete feature, it functions as intended when using a pre-defined chip. Check out image1 for an example: image1 However, when a brand new typed option is entered, it ends up duplicating multiple ti ...

Is there a way to transform this Json array into a format that JQuery can interpret easily?

Having a bit of trouble with this issue. I'm not entirely sure how to get it working correctly. According to Firebug, the Json object (or possibly array) from my ajax request appears as follows: { "jsonResult": "[ {\"OrderInList\":1}, ...

What is the appropriate import to use when working with FontAwesomeIcon, React, and Jest?

Currently, I am working on a React website built with TypeScript and Webpack. I am using FortAwesome's react-fontawesome package to display icons. The import statement for this package is as follows: import FontAwesomeIcon from '@fortawesome/rea ...

"Enhance your Angular configuration with the powerful ngBootbox plugin

Is there a way to permanently change the locale of ngBootbox? I tried adding an extra angular configuration: var app = angular.module('some_module', ['highcharts-ng', 'ui.router', 'oc.lazyLoad', 'ui.selec ...

Method for extracting URL parameters while utilizing a hash within the URL

I've been exploring AJAX with hash in URL using prototypejs. Consider the following URL: http://example.com/#/example/104?v=0&d=a&rpp=10 print_r( $_GET ); // output: array() However, when I try this URL: http://example.com/example/104?v= ...

Locate and eliminate all occurrences of "<br />" within a webpage using jQuery

I am currently working on a project using the Cargo Collective platform and I have noticed that it automatically includes unnecessary <br /> tags in the body of my document. Is there a way to use jQuery to scan for all instances of <br /> tags ...

Using Angular JS to connect Promises while preserving data

There have been discussions about chaining promises, but this scenario presents a unique challenge. I am currently working on making multiple http get requests in my code. The initial call returns an array, and for each object in this array, another http c ...

transferring data to Amazon Web Services using Angular framework

I'm currently facing an issue while trying to send a file to an AWS server using an Angular dropzone. I have my AWS credentials ready, but I am unsure of how to properly make the request. Every time I attempt to drop the file into the dropzone, I kee ...

Resolving the CORS predicament caused by the ionic/angular's HTTP interceptor

I am currently using Ionic for both web and mobile development. However, I have encountered a CORS issue when integrating it with an HTTPS URL. Interestingly, the issue seems to be resolved after removing the HTTP interceptor. Nevertheless, I am seeking a ...

What is the best way to modify the display of a specific section on a page in VueJs 3?

I have three main sections on my webpage, and I am looking to change the view for just one section: <template> <div id="main"> <div id="scene"> <scene/> </div> < ...