Using Vue.js to toggle rendering based on checkbox selection

Struggling to conditionally render form elements in Vue based on user input. I can do this with VanillaJS or jQuery, but struggling to implement it with Vue's built-in conditional directives. Using single-file components with the webpack template from vue-cli.

In my <template>:

<form autocomplete="off" name="loadDeets" id="loadDeets" class="loadDeets">
    <div class="form-group row">
       <label>Date</label>
       <flat-pickr v-model="date"
              :config="{dateFormat: 'l, F j'}"
                class="form-control" 
                placeholder="Select date"               
                name="date"></flat-pickr>
    </div>

    <div class="row">
        <div class="form-group col left">
           <label>Time</label>
           <flat-pickr v-model="time"
                :config="config"
                class="form-control" 
                placeholder="Select time"               
                name="time1"></flat-pickr>
        </div>

        <div class="form-group col right">
            <label>Time</label>
            <flat-pickr
                :config="config"
                class="form-control" 
                placeholder="Select time"               
                name="time2" v-show="document.getElementById('apptCheck').checked"></flat-pickr>
        </div>
    </div>

    <div class="form-check">
        <input class="form-check-input" type="checkbox" id="apptCheck">
        <label class="form-check-label" for="apptCheck">
           Appointment?
        </label>
    </div>
 </form>

However, this setup completely breaks the page’s component rendering. Next, attempted using v-model based on a specific Vue documentation page. Link here

<div class="row">
   <div class="form-group col left">
      <label>Time</label>
      <flat-pickr v-model="time"
           :config="config"
            class="form-control" 
            placeholder="Select time"               
            name="time1"></flat-pickr>
    </div>

    <div class="form-group col right">
       <label>Time</label>
       <flat-pickr
           :config="config"
            class="form-control" 
            placeholder="Select time"               
            name="time2" v-show="vm.checked == true"></flat-pickr>
    </div>
 </div>

 <div class="form-check">
    <input class="form-check-input" type="checkbox" value="checked" id="apptCheck" v-model="checked">
    <label class="form-check-label" for="apptCheck">
        Appointment?
    </label>
 </div>

Unfortunately, implementing this also results in breaking the page.

Feeling unsure about the next steps. Is there a better way of approaching this? Can v-if/v-show not interact effectively with input from other elements?

Answer №1

The proper way to achieve this is shown in your second example. In Vue, it is not necessary to access an element by ID. You can utilize all the variables within your component without using vm., simply use v-show="checked":

<flat-pickr
   :config="config"
    class="form-control" 
    placeholder="Select time"               
    name="time2" v-show="checked"></flat-pickr>

Ensure that you declare checked in your data function as well. Instead of assigning value="checked" to that element initially, set it to true in your initial data and use v-model="checked" for automatic checking.

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 there a way to modify the variable in order to switch the font of the heading every second using CSS and JavaScript?

I'm trying to create a heading that changes fonts every second, but I'm having trouble changing the variable to set it to another font. Check out my code here. Despite watching tutorials, everything seemed too confusing. var root = document.q ...

Ways to pass JavaScript variables to a Python script

Hey there! I'm currently facing an issue with retrieving variables from JS to use in my python code. Despite trying methods like AJAX and JQuery, I haven't had much success yet. It's possible that I'm missing something crucial in the pr ...

"Combining Arrays in Vuex Getters: A Step-by-Step

Is there a way to efficiently update a concatenated array in vuex getters without requiring a hard browser refresh? const state = () => ({ array1 : [{'key1':'value1'}], array2 : [{'key2':'value2'}, {'ke ...

Creating a selection area with CSS that appears transparent is a straightforward process

I'm currently exploring ways to implement a UI effect on a webpage that involves highlighting a specific area while covering the rest of the page with a semi-transparent black overlay, all using CSS only. What is the most common approach to achieving ...

Is it achievable to have a background image cover size with a responsive rollover effect?

I’m currently facing a unique challenge where I want to have an image as the background of my website, with the size set to cover the entire screen. On this background image, there are elements like buildings that I want to interact with when hovered ove ...

Creating a visual representation of the information stored in my JSON data file using a Quasar table

As a VueJS student, I'm struggling to display the distances from my JSON file in a table. What is the best way to retrieve and show all the distance data for "5" and "10" by both walking and driving? Should I use this code: this.concurrentsRows = JSO ...

Encountered an error when attempting to use the 'removeChild' function on a node that is not a child of the specified node. This issue arose while interacting with an input box

I recently created a todo app with a delete functionality. However, after deleting an element successfully, I encountered an error when typing in the input box stating: Failed to execute 'removeChild' on 'Node': The node to be removed i ...

Understanding the JSON output received from the Servlet

So, I have a Java Servlet set up to return JSON data in Application/JSON format using the GSON library. The GET method of the Servlet requires an ID parameter. When I send a request with BookingID as 1, Chrome shows the AJAX response like this: 0: {W ...

What is the best way to access the attributes of a particular object following a triggered event?

I'm a bit unsure if my title makes sense, so allow me to explain. In a nutshell, I have 2 li elements within a ul list. What I aim for is that when one of these li elements is clicked, the text within that particular li is retrieved, and then an obje ...

Encountering a Typescript error while attempting to remove an event that has a FormEvent type

Struggling to remove an event listener in Typescript due to a mismatch between the expected type EventListenerOrEventListenerObject and the actual type of FormEvent: private saveHighScore (event: React.FormEvent<HTMLInputElement>) { This is how I t ...

Having difficulty automatically populating a textarea with the chosen option from a datalist

Is there a way to automatically populate the Address field of a client in a textarea based on the input of the client's name in an input field? I have created a 'for loop' to retrieve a datalist of client names. For the address, I retrieved ...

"Learn to easily create a button within a table using the powerful functionality of the dataTable

I need to add a button to each row in a table. I managed to achieve this with the code below, but there's a problem - every time I switch between pages, the button keeps getting added again and again. It seems like the button is generated multiple tim ...

There are critical vulnerabilities in preact-cli, and trying to run npm audit fix leads to a never-ending loop between versions 3.0.5 and 2.2.1

Currently in the process of setting up a preact project using preact-cli: npx --version # 7.4.0 npx preact-cli create typescript frontend Upon completion, the following information is provided: ... added 1947 packages, and audited 1948 packages in 31s 12 ...

Numerous toggles available for the mobile version

Hey there, I need some help! I have a footer navigation on my desktop website with 3 Ul elements. I want to turn each Ul into a toggle for the mobile version. Can anyone assist me with this? Thanks in advance! <footer class="footer"> <d ...

Encountering an unusual hash code when implementing Google Tag Manager in a Next.js project was

I am currently using Next.js and have added Google Tag Manager through a script <script dangerouslySetInnerHTML={{ __html: `(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start': new Date().getTime(),event:'gtm.js'});var ...

The Vue website on S3 is experiencing a 404 error, but it is still able to

I'm facing an issue with my Vue2 site where everything seems to be working fine for the users, but Google is flagging most of the pages as having 404 errors. Even though when accessing a direct URL like hptts://example.com/example, the page loads corr ...

The Angular component fails to retrieve data from a subscribed service when the data is being fetched from the sessionStorage

Within my Angular application, there exists a service that handles incoming objects by adding them to a list of objects, then saving the updated array to sessionStorage. This service also sends the updated list to another application that is subscribed to ...

npm's protocol for handling callback errors

While exploring the coding style guidelines by npm, I stumbled upon a rather enigmatic suggestion: Be very careful never to ever ever throw anything. It’s worse than useless. Just send the error message back as the first argument to the callback. Thi ...

Tips for activating an HTML input field using Javascript

I am currently using localStorage to store a string input by the user as a title, which will be saved for future visits. I would like to implement a button that allows the user to delete the displayed text (from localstorage) and enables the input field fo ...

Exploring the world of color in Google visualization charts

I am currently working on a project that requires me to add different colors to specific zones on a graph. I am looking to use colors such as blue, red, yellow, and green. Here is the outcome I have achieved: I am aiming for something similar to this des ...