Steps to update the color of checkbox labels

I'm struggling with changing the colors of checkbox values based on their status - when checked, I want the text to display in green, and when unchecked, I want it to be red. Below is a sample input type, but I can't figure out how to style the true-value and false-value. If anyone has suggestions, please help! Thanks! Here's the complete code for reference.

            <label>Other Information:</label>
            <textarea v-model="student.otherInformation"></textarea> <br /><br />

            <input type="checkbox" v-model="student.agree" true-value="I want to receive promotions"
            false-value="I Don't want to receive promotions">

            <span>Agree receive our promotions.</span><br><br>
            <button type="submit" class="button" >Add a new student</button>
        </form>
    

Answer №1

To apply a style in Vue.js:

new Vue({
  el: '#demo',
  data() {
    return {
      user: {name: "", age: 0, country: ""},
      users: [{name: "John", age: 28, country: "US"}, {name: "Alice", age: 25, country: "UK"}],
      countries: ["US", "UK", "CA"],
    }
  },
  methods: {
    addUser() {
      this.users.push(this.user)
    },
    removeUser(index) {
      this.users.splice(index, 1);
    },
    selectCountry(country) {
      this.user.country = country;
    },
    // 👇 method for selecting style
    applyStyle(i) {
      return this.users[i].age > 25 ? 'color: blue' : 'color: black'
    },
  },
})
.over-25 {
  color: Blue;
}
.under-25 {
  color: Black;
}
.btn-primary {
  background-color: transparent;
  border: 1px solid #3498db;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="demo">
  <h3>User Details</h3><hr>
  <form class="basic-grey" @submit.prevent="addUser">
    <label for="name">Name:</label>
    <input id="name" type="text" required v-model="user.name">
    <label for="age">Age:</label>
    <input id="age" type="number" v-model="user.age">
    <label>Country:</label>
    <select v-model="user.country">
      <option disabled selected value="">Please select your country</option>
      <option v-for="country in countries" :key="country">{{ country }}</option>
    </select>
    <button type="submit" class="button">Add User</button>
  </form>
  {{ user }}
  <h3>Users List</h3><hr>
  <table>
    <thead>
      <th>Name</th>
      <th>Age</th>
      <th>Country</th>
      <th>Action</th>
    </thead>
    <tbody>
      <tr v-for="(u, index) in users">
        <td>{{ u.name }}</td>
        <td :style="applyStyle(index)">{{ u.age }}</td>
        <td>{{ u.country }}</td>
        <td><button class="btn-primary" @click="removeUser(index)">Remove</button></td>
      </tr>
    </tbody>
  </table>
</div>

Answer №2

Although I am not familiar with Vue, you can achieve the desired result using plain HTML and CSS

<!DOCTYPE html>
<html>
<style>
/* Custom checkbox styles */
.container {
  display: block;
  position: relative;
  padding-left: 35px;
  margin-bottom: 12px;
  cursor: pointer;
  font-size: 22px;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
}

/* Hide default checkbox */
.container input {
  position: absolute;
  opacity: 0;
  cursor: pointer;
  height: 0;
  width: 0;
}

/* Custom checkbox design */
.checkmark {
  position: absolute;
  top: 0;
  left: 0;
  height: 25px;
  width: 25px;
  background-color: #F00;
}

/* Change color when checked */
.container input:checked ~ .checkmark {
  background-color: #00FF00;
}

/* Checkmark design */
.checkmark:after {
  content: "";
  position: absolute;
  display: none;
}

/* Show checkmark when checked */
.container input:checked ~ .checkmark:after {
  display: block;
}

/* Style checkmark */
.container .checkmark:after {
  left: 9px;
  top: 5px;
  width: 5px;
  height: 10px;
  border: solid white;
  border-width: 0 3px 3px 0;
  transform: rotate(45deg);
}
</style>
<body>

<h1>Custom Checkboxes</h1>
<label class="container">One
  <input type="checkbox" checked="checked">
  <span class="checkmark"></span>
</label>
<label class="container">Two
  <input type="checkbox">
  <span class="checkmark"></span>
</label>
<label class="container">Three
  <input type="checkbox">
  <span class="checkmark"></span>
</label>
<label class="container">Four
  <input type="checkbox">
  <span class="checkmark"></span>
</label>

</body>
</html>

Answer №3

To start, ensure your text is wrapped in semantic HTML elements such as the label tag. Once you have done that, you can use the following code to specifically style the input when checked or unchecked:

input[type="checkbox"]+* {
        font-weight: bold !important;
    }

    input[type="checkbox"]:checked+* {
        text-decoration: underline !important;
    }

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 duration of recorded audio in JavaScript is unclear

I managed to successfully create a structure for recording and downloading audio files. However, I'm facing an issue where the final downloaded file has an unknown duration. Is there any way to solve this problem?? Here is my Typescript code snippet: ...

Using the power of jQuery and Ajax to smoothly transition to a different page after editing the value of

Displaying a MySQL table named demo with the values Peter and John along with edit links Example Peter EDIT John EDIT When the edit link is clicked, it will open the page edit_name.php. In edit_name.php, you can update the clicked value using the updat ...

What causes React JS to continuously render in an infinite loop when using hooks and useState

I am struggling with updating the current state of my component based on a result using a custom hook in React. Whenever I try to update it, I end up in an infinite loop rendering due to my usage of the useState() hook. I am still new to working with Rea ...

What is the best way to send a promise back from my service to my controller?

While I have posed this question in various forms, I now find myself stuck with a piece of code that contains an elusive bug. My Angular service looks like this: .service("lookupDataService", [ '$q', '$http', '$timeout&ap ...

Developing Your Own Local Variable in Angular with Custom Structural Directive ngForIn

I am hoping for a clear understanding of this situation. To address the issue, I developed a custom ngForIn directive to extract the keys from an object. It functions correctly with the code provided below: import {Directive, Input, OnChanges, SimpleChan ...

Guide on displaying a real-time "Last Refreshed" message on a webpage that automatically updates to show the time passed since the last API request

Hey all, I recently started my journey into web development and I'm working on a feature to display "Last Refreshed ago" on the webpage. I came across this website which inspired me. What I aim to achieve is to show text like "Last Refreshed 1 sec ago ...

The search button is malfunctioning after I submit search data and generate dynamic HTML using axios

When a user clicks on the search button, I retrieve the input value and then use axios to send a GET request with the search data. Everything works fine, but when I query the database and dynamically create data from the mongoose data, the page reloads w ...

Storing user input from a form into a MongoDB database using a webhook function

I've been struggling to store form data in my MongoDB database for quite some time. Additionally, I receive a response from the database. Check out this resource: create object in mongo db api onclick sending form Unfortunately, there is a lack of ...

Tips for guaranteeing that the value is retained in an array when setting a Cookie in AEM/cq5

I'm facing an issue with AEM where the page path needs to be added to a cookie each time a user visits a specific type of page. The requirement is to store a maximum of 3 pages in the recently visited section of the cookie. Initially, I attempted to u ...

`vuetify sidebar with a nested menu``

I am trying to enhance the vuetify sidebar menu I created by adding a submenu to a specific title. Despite editing the code and data as shown below, I am unable to see any changes reflected. Below is the code snippet: <v-list flat class="mt- ...

What is the best way to format 100K to appear as 100,000?

function formatNumberWithCommas(num) { return num >= 1000 ? `${Number.parseFloat((num).toFixed(3))}` : num; } ...

Using CSS to automatically adjust the width of a child div based on its content, rather than stretching it to fill the entire

I'm currently facing an issue with my CSS. Apologies for the vague title, but I'll do my best to explain it here. My problem lies within a parent wrapper div that is centered on the page. Within this wrapper, there is another child div containing ...

What could be causing the issue with the theme not functioning properly in Material-UI?

I'm currently working on implementing a unique theme-switching feature in my web application, allowing users to toggle between light and dark modes. Utilizing the Material-UI framework combined with React, here's the code snippet: const theme = c ...

AngularJS Datepicker - calendar dropdown does not update when the model changes

I've been facing a challenge with the AngularJs datepicker in my project for some time now. Within my application, users have the option to either manually select a date using the calendar or click on "This Month" to automatically set the date to the ...

Preventing click propagation for custom react components nested within a MapContainer

I have developed a custom control React component for a map as shown below: export const MapZoom = () => { const map = useMap() const handleButtonClick = () => { map.zoomIn() } return ( <IconButton aria ...

The AngularJs project is currently experiencing issues when trying to function as a single page web application

I'm currently working on incorporating AngularJS into an existing web project that uses jQuery. Here is a snippet of my code: <div class="medya" ng-repeat="d in data" masonry-item-dir> <a href="{{d.Url}}" class="onizleme"><img src="{ ...

What could be causing the triggering of two AJAX requests in the given JavaScript code?

I have a code snippet that fetches data from the server. I want to trigger it on document.ready(). My expectation is that the first request is sent to the server, receives a response, and then the second request is made, and so forth. However, when I insp ...

Managing key presses with functions in VueJs

Within my component, I am utilizing VueStrap's modal in the following manner: <template> <modal-window v-model="show" v-on:keyup="keyHandler($event)" @ok="submit()" @cancel="cancel()" @closed=" ...

Enhance User Experience by Implementing Event Listeners for Changing Link Visibility Using mouseover and getElementsBy

I am new to JavaScript and struggling to find a solution. Despite searching online for fixes, none of the solutions I've found seem to work for me. I have spent hours troubleshooting the issue but I must be missing something crucial. Can someone plea ...

How can I include a nested object in an ng-repeat loop in Angular?

I'm new to using Angular so please excuse my basic question. Here is the structure of my model for posts and comments: [ { "title": "awesome post", "desc": "asdf", "comment_set": [ { "id": 2, ...