Using VueJs to associate boolean values with dropdowns

I am currently working on a form with a dropdown menu containing two options: "True" and "False". My goal is to save the selected value as a boolean in the form.

For instance, when the user selects "True", I want the value stored as true in boolean format.

<select v-model="selected">
  <option :value="null">Pick a value</option>
  <option v-for="val in options">{{val}}</option>
</select>

...

data() {
 return {
  selected: null,
   options: ["true", "false"]
}

If you'd like to see what I'm working on, here's a fiddle link: https://jsfiddle.net/q0nk9h32/5/

Do you have any suggestions on how I can display the selected values in their boolean form?

As a bonus question: Instead of using the options variable, would it be considered valid syntax or good practice to use:

v-for="val in ["true", "false"]" ?

I feel like having a separate variable for this might be unnecessary (but when I tried using an array directly, it failed in the fiddle). Appreciate any insights!

Answer №1

To assign a value to each <option>, you can use the :value attribute.

Click here for more information on Select Options in Vue.js

new Vue({
    el: '#app',
    data() {
        return {
            selected: null
        }
    }
});
<script src="https://unpkg.com/vue"></script>

<div id="app">
    <select v-model="selected">
        <option :value="null">Pick a value</option>
        <option v-for="val in [true, false]" :value="val">{{val}}!!!</option>
    </select>
    <p>
        Selected is the {{ typeof selected }}: {{ selected }}
    </p>
</div>

If you want, you can define the array directly within the v-for. Keep in mind that when using double quotes around strings, it may conflict with existing double quotes in attributes.

There are multiple ways to display the text as True and False for these values...

In particular cases where there are only two values, such as true and false, you might consider skipping the v-for loop and manually writing the options.

<option :value="null">Pick a value</option>
<option :value="true">True</option>
<option :value="false">False</option>

Alternatively, you could utilize a filter or method to format the text accordingly. Here are examples:

<option v-for="val in [true, false]" :value="val">{{ val | filter }}</option>

or

<option v-for="val in [true, false]" :value="val">{{ method(val) }}</option>

To implement a filter, define it in the component's filters section. For a method, place it in the methods. The function should convert the boolean value to a string and capitalize the first letter.

// This method could be named differently...
method (value) {
    const str = String(value);
    return str.charAt(0).toUpperCase() + str.slice(1);
}

Considering there are only two options, several other approaches can achieve the same result. For instance:

<option v-for="val in [true, false]" :value="val">{{ val ? 'True' : 'False' }}</option>

Answer №2

An alternative approach could involve implementing a computed property that simply evaluates whether this.selected is equal to 'true'.

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

Team members

Just started diving into Angular and practicing coding with it while following video tutorials. However, I've stumbled upon something in my code that has left me puzzled. I'm curious about the significance of the line "employees: Employee[]" in ...

including a collection of values into a JSON data structure

Currently, I am iterating through some JSON data (grouped tweets from Twitter) to tally the frequency of specific keywords (hashtags) in order to generate an organized list of common terms. this (19) that (9) hat (3) I have achieved this by initial ...

What is the best way to update a specific section of my website by modifying the URL while keeping the menus fixed and the site functioning smoothly?

I am in desperate need of assistance as I search for a solution. Currently, I am working on a project involving music within a web browser or application. My goal is to utilize HTML, PHP, JS, and CSS to create this project. If I start with a website, I p ...

Ways to retrieve the chosen option in a dropdown list without specifying the dropdown's name, id,

Custom dropdown, Model-View-Controller Code @foreach (var attribute in Model) { string controlId = string.Format("product_attribute_{0}_{1}_{2}", attribute.ProductId, attribute.ProductAttributeId, attribute.Id); @switch (attribute.AttributeControl ...

The issue with dynamic sizing in React and Tailwind is that it does not consistently work with arbitrary sizes. Some sizes do not appear properly, causing items to

In this code snippet, I am attempting to create a circle component of dynamically sized using html div and Tailwind CSS w-[diameter] & h-[diameter] attributes in a create-next-app@latest project. However, the circle fails to render properly with certa ...

Exploring ways to retrieve global variables within a required() file in Node.js

Imagine having 2 files: main.js, and module.js: //main.js const myModule = require('./module'); let A = 'a'; myModule.log(); //module.js module.exports = { log() { console.log(A); } } After trying to call myModule.log, ...

`Is it necessary to handle textStatus when encountering an HTTP error during an AJAX request?`

When utilizing jQuery and encountering an AJAX request failure attributed to an HTTP error (e.g., 500 Internal Server Error), what exactly is the assigned value of the textStatus parameter within the error handler function? For instance, $.ajax(...).fail( ...

Connect data from an HTML table depending on the chosen option in a dropdown menu using AngularJS, JQuery, JSON, and

Could you please correct my errors? It's not working as I have made some mistakes. I need an HTML table based on the selection. I have tried but cannot find a solution. I created a dropdown, and if I select any value from the dropdown and click a butt ...

Restricting user access to a route based on its type to enhance security and control

Currently, I have a React, Redux, and Next.js app up and running. Within my redux store, there is a user object that contains an attribute called "type". Each type of user has its own set of "routes" they are allowed to access. I am looking for the most e ...

Exploring the depths of object properties with Angular, JavaScript, and TypeScript: A recursive journey

Let's consider an object that looks like this: const person = { id: 1, name: 'Emily', age: 28, family: { mother: { id: 101, name: 'Diana', age: 55 }, fathe ...

The onclick functionality is not functioning properly within email communications

My JavaScript code contains an AJAX call within Datatables, and this snippet of code is causing an issue: { "data": null, "width": "10%", "render": function(data){ icon2 = '<center><button type="button" class="btn btn-info ...

Utilizing jQuery for serializing unorganized lists

I have created multiple lists within a list and I need to pass the IDs using jQuery to another PHP file (updateDB.php). I attempted to serialize the list data but was unsuccessful. I'm not certain if I have implemented it correctly, I searched extens ...

I am running into issues getting Tailwind CSS to work in my project. Despite following the installation instructions in the documentation and trying to learn this new CSS framework, it doesn't seem to

//I followed the instructions in the tailwind documentation to install and set up everything. However, when I try to use tailwind utility classes in my HTML file, they don't seem to work. Can someone please assist me with this issue? // Here is my sr ...

Obtain the value of an element from the Ajax response

Just starting out with Jquery and Ajax calls - here's what I've got: $(document).ready(function () { $.ajax({ type: "GET", url: "some url", success: function(response){ console.log(response); } }) }); Here's the ...

Executable program contained within npm bundle

I am working on creating an npm package that can be executed as a command from the shell. I have a package.json { "name": "myapp", "version": "0.0.6", "dependencies": { "async": "", "watch": "", "node-promise": "", "rmdir": "", " ...

Assign tags using a variable within a loop

Consider the scenario where I need to generate a list of li elements: {map(listItems, (obj,i) => <li key={i}> <a target="_blank" href={obj.itemName === 'view_detail' ? `event/${id}` : ''} > <i c ...

What are the steps to create a connect4 board featuring rounded corners and curved sides?

How can I create a Connect4 board with the exact styles and properties shown in the image? I want to achieve the curved sides effect as displayed. Can this be done using only HTML elements, or is there an easy SVG solution available? Here is my current co ...

Combining Rxjs map and filter to extract countries and their corresponding states from a JSON dataset

I have a unique dataset in JSON format that includes information about countries and states. For example: { "countries": [ { "id": 1, "name": "United States" }, { "id": 2, "name": "India" }], "states": [ { ...

Incorporating a polygon into vue2-leaflet framework

I have been struggling to incorporate a MultiPolygon onto a leaflet map using vue2-leaflet without any success. The polygon coordinates are being generated from PostGIS. Is there a way to add a polygon to a vue2leaflet map? Sample code: fiddle: https:// ...

Using Javascript to create a new regular expression, we can now read patterns in from

I am currently working on developing a bbcode filtering solution that is compatible with both PHP and JavaScript. Primarily focusing on the JavaScript aspect at the moment, I have encountered an issue with the new RegExp constructor not recognizing pattern ...