Developing a function triggered by the click of a checkbox

My task here is to create a function that will show the "is the spa" section when the user clicks on the "Spa" checkbox. This particular project uses Laravel and Vue.js.


Below is the Bootstrap-Vue code I implemented for checkboxes:

 <template>
    <b-form-group label="Construction is a: ">
            <b-form-checkbox-group
            v-model="selected"
            :options="options"
            name="flavour-2a"
            stacked
            ></b-form-checkbox-group>
    </b-form-group>
</template>

<script>
    selected: [], // Must be an array reference!
    options: [
      { text: 'Pool', value: 'pool' },
      { text: 'Spa', value: 'spa' },
      { text: 'Pool & Spa', value: 'poolAndSpa'},         
      
      ],
</script>

// **Function implementation starts here**,
 <b-form-group label="Construction is a: ">
            <b-form-radio-group
            v-model="selected"
            :options="options"
            name="poolConstruction"
            @change="radioChange($event)"
            stacked
            ></b-form-radio-group>
        </b-form-group> 

       radioChange: function(e) {
        if(this.selected == "spa"||"poolAndSpa"){
            
            document.getElementById("spaRadio").style.display = "block";
        }else
                        
        {
        document.getElementById("spaRadio").style.display = "none";
        }

Answer №1

To start off, let's clarify your requirements.

  1. Your goal is to trigger a method every time the checkbox is clicked
  2. Within the method, you will check the value of the clicked checkbox
  3. If the value of the checkbox is 'spa', then show the radio button; otherwise, hide it

Here is the HTML code structure where you can insert your radio button code inside the div with spaRadio Id. We have included an @change method on the checkboxes and the rest remains the same.

<div id="app">
  <b-container>
    <b-row>    
     <b-form-group class="mx-auto">
        <b-form-checkbox-group buttons @change="handleChange($event)"  name="buttons1" class="customCheck1" :options="chartOptions" v-customcheckbox="chartOptions">
        </b-form-checkbox-group>
      </b-form-group>      
    </b-row>
    <b-row>
       <p class="mx-auto"gt;  Selected:  {{ charts }}</p>
    </b-row> 
    <div id="spaRadio" class="hide">
        <p>Radio buttons here<p>
    </div>
  </b-container>
</div>

Subsequently, within the method, we are going to introduce a condition to check if the value matches 'spa' or 'poolAndSpa'. This involves comparing the selected value with each expected filter keyword.

this.selected == "spa"||"poolAndSpa"

The correct comparison should be:

(this.selected == "spa" || this.selected == "poolAndSpa")

Method:

methods: {
    handleChange: function(e) {
        const name = e;
        this.selected = name; // Assign the selected value
        let result = this.selected.find(el => (el === "spa") || (el === "poolAndSpa")); // Search for the filter keywords 'spa' or 'poolAndSpa'
        if(result !== undefined){ // If any of them is found, display the radio button; else hide it
          document.getElementById("spaRadio").style.display = "block";
        }else {
          document.getElementById("spaRadio").style.display = "none";
        }
    }
},

Working example: https://codepen.io/AhmedKhan1/pen/LYNQNmw

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

Error in syntax: The tailwind import statement contains an unrecognized word and will not function correctly

After configuring Tailwind CSS with Next.js, I made changes to the tailwind.config.js file. However, after making these changes, the compilation process failed and resulted in the following error: Error - ./src/assets/styles/global.css:3:1 Syntax error: Un ...

The issue with Firefox's DOMContentLoaded event

After creating a script that interacts with the Dom, I noticed that it needs to wait until the Dom is ready before executing each operation. My intention is to make this script usable in two ways: Include it in the head tag, ensuring it loads before the ...

Arrange the Json array by key value in a different order

I have a contact list that is returning in a lengthy form, organized based on order of entry. I am looking to alphabetically sort the list by displayName which is nested within the main array. Can anyone assist with this challenge using JavaScript? Thank ...

What is the standard method for setting universal variables in Vue.js?

As I work on developing Vue applications with single file components, I have noticed that many of my components require common configuration information. For instance, I often need to define an object containing various delivery methods like this: const De ...

The chosen option does not equal the value retrieved by using jQuery's

I am perplexed by the situation at hand. It seems that there is a discrepancy in the selected option of my select element. Despite appearing as the empty default option on top, the inspected element reveals it displaying a value of 13. https://i.sstatic.n ...

Using jQuery to create a multiselect feature and selectable options

Having trouble with jQuery multiselect and selectable? I've got some ideas about what might be going wrong. I suspect the issue lies in the index changing when splicing items. Despite my attempts, I can't find a solution. Your assistance would ...

Setting up Vite dev server to run through a port proxy path: A step-by-step guide

Exploring the use of Vite dev server in a cloud-based development setup where it's possible to serve on and connect to ports, but access must be through a proxy path. Instead of typing http://localhost:3000/index.html, the goal is to reach https://my ...

Utilizing AjaxChosen for event handling

I am currently experimenting with a jQuery plugin that can be found here: https://github.com/meltingice/ajax-chosen. I have a multiple select field and I am curious about which event is triggered when a user either deletes or selects a value. Here are the ...

Ways to determine the current page I am viewing

I am working with a list of tabs and I need to track my current location every time I click on a specific tab. My MainCTRL controller, which is the parent of all tab controllers, needs to be aware of the active tab at any given moment. I attempted to use n ...

NodeJs Classes TypeError: Unable to access 'name' property as it is undefined

I am currently developing a useful API using Node.js. In order to organize my code effectively, I have created a UserController class where I plan to include all the necessary methods. One thing I am struggling with is how to utilize a variable that I set ...

The value of an AngularJS model object cannot be altered with a dynamic key

app.controller('indexController', ['$scope', '$location', 'authService', function ($scope, $location, authService) { var vm = this; vm.$onInit = function () { vm.active = { "home": true, ...

What's the most effective method for isolating elements in HTML to prevent one element from impacting another?

I recently created a password form in HTML with some nice functions. However, after making a small adjustment, the CSS is causing the elements to shift when clicking on different input boxes. This results in the labels on the form moving slightly up and do ...

Getting values from DOM controls can be tricky when models are being dynamically created with Vue.js. Here's a guide on extracting these

I'm currently developing a form generator component that dynamically populates DOM controls from an API service. The model key, represented by :v-model, is also generated dynamically. However, I'm encountering issues accessing the user-input data ...

Retrieve a particular element from a JavaScript object by iterating through it with the .each()

Welcome, fellow developers! I am currently facing a challenge in my ticketing system project involving getting the 'title' variable from a node.js loop. The objective is to use this variable as a placeholder so that when a user wants to edit a t ...

The act of coming back with just one array

I'm having trouble grasping the concept of returning a single array from a function that calls another function multiple times. The issue I'm facing is that each time the scrapingfunction runs, the console.log in the code provided outputs an arra ...

Creating a dynamic nested list in HTML using JavaScript with data retrieved from a JSON source

I'm trying to generate a dynamic nested ul\li list from a JSON array. IMPORTANT! While I can use jQuery for this transformation, it's in a node.js environment where DOM access is restricted and I must work with a string. The depth of the a ...

Having trouble configuring CORS in Sails.js for fetching Google Maps geolocation data?

Struggling to enable CORS in my local app, I've been following the sails.js documentation which suggests changing the setting "allRoutes: true" for enabling cors. However, when attempting to access the Google API using Angular: getLocation: function( ...

Changing a millisecond date string into a human-readable date format using jQuery

Seeking a way to transform milliseconds into a readable date format, I encountered a roadblock. Despite my extensive search for a solution, none of them seem to address my issue. I'm aiming to make val.start display as 10.15, but it currently shows: ...

The external IP address cannot be accessed beyond the function scope in Node.js

Recently joining this community, I am in the process of retrieving my external IP through a package called "external-ip." The example code provided by them looks like this: const getIP = require('external-ip')(); getIP((err, ip) => { ...

Generating a container DIV with loops and ng-class in AngularJS

Currently, I am working on developing a dynamic timeline using AngularJS. To populate my timeline, I have successfully configured the data fetching from a JSON file. You can see what I have accomplished so far on PLNKR: http://plnkr.co/edit/avRkVJNJMs4Ig5m ...