Learn how to dynamically set the "selected" option in Vue based on object data

I've done some digging on SO but haven't found exactly what I need.

So, here's the situation - I've got a sorting function in progress. I have an array of date ranges (PayPeriods) that I want to render into a select with option components using v-for. Here's an example:

<time-clock-group-component
v-for="(timeClockGroup, index) in timeClockGroups"
:key="`timeClockGroup-${index}`"
:timeClocks="timeClockGroups[index]"
/>

The component is pretty straightforward:

<template>
  <option>{{ Start }} - {{ End }}</option>
</template>

My goal is to automatically select the last rendered component so it loads the most recent data without needing user input. I have a bool key:value setup on the PayPeriod object that I thought could work for this, but I'm struggling to implement it. I tried using a mounted check like this:

if (this.payPeriod.Current) {
      document.getElementById(
        "ppc"
      ).innerHTML = `<option selected>{{ Start }} - {{ End }}</option>`;
    }

However, I'm getting the error message "Cannot set property 'innerHTML' of null," which I suspect might be related to something in Vue?

Answer №1

Avoid mixing document with Vue for better practice.

If you are looking to automatically select the last element, consider creating a prop named selected inside your TimeClockGroupComponent. This prop can be set as true for the last element in the array.

You could make these changes:

<!-- parent.vue -->
<time-clock-group-component
  v-for="(timeClockGroup, index) in timeClockGroups"
  :key="`timeClockGroup-${index}`"
  :timeClocks="timeClockGroups[index]",
  :selected="timeClockGroups.length === i + 1"
/>

And:

// TimeClockGroupComponent.vue
<template>
  <option :selected="selected">{{ Start }} - {{ End }}</option>
</template>
// ...
  props: {
    // ...
    selected: {
      type: Boolean,
      default: () => false
    }
  }

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

Establish map boundaries using the longitude and latitude of multiple markers

Utilizing Vue, I have integrated the vue-mapbox component from this location: I've made sure to update the js and css to the latest versions and added them to the index.html: <!-- Mapbox GL CSS --> <link href="https://api.tiles.mapbox.com/m ...

Javascript clock problem, kick off on click

Currently working on a game and in need of a counter that starts when clicked and stops at 00 (From 1m to 00). It is currently starting onload and cycles back to start when it reaches 00. HTML: <body> <div> <div class="timer" >Battle t ...

Could anyone clarify the workings of the async function in this specific useEffect situation?

Within a child component, there is an onClick event: onClick={()=>{ //2. an image is clicked, and the choice is added to the choiceOrder state, and then a jsonupdate is called -- 3. in ChooseBy.js //onclick, add or remove the choice choosebyprop ...

What is the reason for the additional line being generated?

Can anyone explain why there is an extra line being produced here? I came across another question where it was mentioned that this issue is not due to CSS but rather caused by HTML. Why is that? This is completely new to me, and I'm curious as to wh ...

Encountering insurmountable obstacles in accessing AliExpress

I'm looking to extract specific information from aliexpress using scrapy and selenium. However, I've encountered an issue where the HTML code appears differently when inspecting with Chrome compared to viewing the source. It seems that the conte ...

Vite-Vue3 does not support web components in either its full build or runtime compiler

1. Update vite.config.js to include full vue build: import { defineConfig } from 'vite' import vue from '@vitejs/plugin-vue' export default defineConfig({ plugins: [vue()], resolve: { alias: { 'vue': 'vue ...

The CSRF token is mysteriously altering in places it should remain unchanged

Implementing the code below to prevent CSRF vulnerability if (!isset($_POST['_token'])) { $_SESSION['_token'] = bin2hex(random_bytes(20)); } I then use the token in hidden inputs named _token. In my main.js file, I include the foll ...

Organizing Parsed JSON Data with JavaScript: Using the _.each function for Sorting

var Scriptures = JSON.parse( fs.readFileSync(scriptures.json, 'utf8') ); _.each(Scriptures, function (s, Scripture) { return Scripture; }); This code extracts and displays the names of each book from a collection of scriptures (e.g., Genesis, ...

Tips for keeping a consistently viewable and editable iteration of your HTML form

How can I efficiently maintain both viewable and editable versions of the same HTML form? I am working on an application that has numerous custom data-entry screens with a high number of fields, and managing separate layouts for viewable and editable form ...

Unable to retrieve scope variable within AJAX call

I am currently in the process of running a loop function that contains an AJAX request within it. However, I am facing difficulties with the success function on the AJAX not being able to access a counter variable outside of the loop function. var upda ...

When using the HTML code <p></p>, the empty paragraph tag does not create a line break

We have a .NET application that saves messages in axml format. Our task is to convert these messages into html. After some research, I came across a 3rd party library called "HtmlFromXamlConverter" that does this job, but with one issue: when the axml cont ...

Is it possible to utilize curly brackets in JavaScript for dividing code segments?

Check out this code snippet. I'm curious if there are any potential drawbacks to using it. //some example code var x = "hello"; { var y = "nice"; function myfunction() { //perform tasks... } } One advantage I see in utilizing t ...

CSS - Discovering the reason behind the movement of text post generation (animation)

I have a question regarding CSS animation, specifically the typewriting effect. I was able to successfully achieve the typewriting effect using animation. However, I noticed that even though I did not set any animation for transforming, once the text is g ...

Create a dynamic animation effect by making a div slide on and off the screen

I'm having trouble figuring out how to make my div slide with a toggle button. I attempted to use variables, but since I have multiple instances of this, it's becoming too complicated to keep track of all the clicks on each one. $(document).r ...

Is there a way to access the original query string without it being automatically altered by the browser?

I'm currently encountering an issue with query strings. When I send an activation link via email, the link contains a query string including a user activation token. Here's an example of the link: http://localhost:3000/#/activation?activation_cod ...

Enrollment in the course is conditional on two words being a perfect match

I have a concept in mind, but I'm struggling to piece it together. I have bits of different methods that just don't seem to align. That's why I'm reaching out for your expertise. Let's say I have 3 content containers with the clas ...

What steps should I take to solve this wheel-related issue in my Vue 3 application?

I have been developing a Single Page Application (SPA) using Vue 3, TypeScript, and The Movie Database (TMDB). Currently, I am tackling the implementation of a search feature and I've encountered a bug. The "search-box" component is located in src&b ...

Is there a way to verify the file extension in a multi-input form during an upload process?

I am looking for a solution that requests users to upload 4 different files when filling out the form. Check out this example of one of the inputs: <div class="custom-file"> <input type="file" class="custom-file-input" accept="video/*" id="v ...

Learn how to dynamically insert an element into an angular scope using a click event

Currently, I am working on a function called onGroundUserClick within the Scope passedScope. The goal is to have a function triggered upon the completion of loading the iframe that will establish ng-click. var $tdName = $("<td/>", { ...

The b-dropdown component is failing to display the designated CSS class

I'm utilizing bootstrap-vue to incorporate <b-dropdown> components, however, the button isn't reflecting any css class changes. Could this be a bug with the bootstrap-vue component or am I making a mistake when adding a class? new Vue( ...