Implementing the disabled attribute in input text fields with Vue.js

There are 2 URLs that I am working with:

  • /register

  • /register?sponsor=4

The first route, /register, provides a clean input field where users can type freely. The second route, on the other hand, pre-fills the input with a value of 4 and disables it, preventing any modifications by users.

I have successfully managed to retrieve parameters dynamically from the router using vue-router. However, when I access the /register route, the input starts as clean but gets disabled after typing just one character.

This is what I have attempted so far:

<input :disabled="sponsor ? true : false" v-model="sponsor" id="sponsor" type="number" class="form-control" name="sponsor" value="" required tabindex="14">

Javascript (Vue.js)

<script type="text/javascript>
    var router = new VueRouter({
        mode: 'history',
        routes: []
    });
    new Vue({
        router,
        el: '#app',
        data () {
            return {
                cities: [],
                city: '',
                selectedCountry: '',
                sponsor: null
            }
        },
        mounted: function() {
            if (this.$route.query.sponsor) {
                this.sponsor = this.$route.query.sponsor
                console.log(this.sponsor)
            }
        },
        methods: {
            onChangeCountry() {
                axios.get('http://localhost:8000/api/cities/country/' + this.selectedCountry)
                .then(response => this.cities = response.data)
                .catch(error => console.log(error))
            }
        }
    });
</script>

Answer №1

Deactivated is considered a Boolean attribute.

Essentially, the presence of the attribute indicates that the input is not active.

The only valid values for the disabled attribute are "deactivated" and "".

Therefore, these three versions are acceptable to create a disabled input:

<input deactivated ... />

or

<input deactivated="" ... />

or

<input deactivated="deactivated" ... />

If you try

<input deactivated="false" ... /> 

it will still disable the input because of the presence of the attribute disabled - despite being invalid HTML due to an unauthorized attribute value.

See it in action here:

<input type="text" disabled="false" />

To resolve this issue, you must ensure not to include the attribute on the input if you don't intend to deactivate it.

Edit: Vue.js founders have addressed this:

For boolean attributes where their existence implies true, v-bind functions differently. For instance:

<button v-bind:disabled="isButtonDisabled">Button</button>

If isButtonDisabled has a value of null, undefined, or false, the disabled attribute will be omitted from the rendered element entirely.

https://v2.vuejs.org/v2/guide/syntax.html#Attributes

Answer №2

One issue in this scenario is that when you bind the input value to 'sponsor' using v-model="sponsor", the input gets disabled as soon as you start typing.

To resolve this, you need to create a flag to determine if the sponsor value is coming from the route and apply the disable logic based on that flag. Alternatively, you can directly use $route.query.sponsor in the :disabled attribute (:disabled="$route.query.sponsor")

<input :disabled="isFromRoute" v-model="sponsor" />

mounted: function() {
  if (this.$route.query.sponsor) {
    this.sponsor = this.$route.query.sponsor
    this.isFromRoute = true // Set the flag - ensure it's included in your data section
  }
},

Answer №3

Give this a shot:

<input :disabled="$route.query.sponsor ? true : false" v-model="sponsor" id="sponsor" type="number" class="form-control" name="sponsor" value="" required tabindex="14">

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

Assign a value to a HubSpot hidden form field by utilizing Javascript

I have a snippet of JavaScript code placed in the head section of my website: <!-- Form ID Setter --> <script> document.querySelector('input[name=form_submission_id]').value = new Date(); </script> My objective is to automat ...

Prevent the transmission of keydown events from dat.GUI to the Three.js scene to maintain event isolation

This code snippet (below) contains 2 event listeners: renderer.domElement.addEventListener("pointerdown", changeColor, false); document.addEventListener("keydown", changeColor, false); Both of these event listeners trigger a color chan ...

Utilizing asynchronous programming for scenarios where two requests need to be sent, with the response from the first request being required for the second request

I have an async function that looks like this: exports.myFunction = async (req, res, next) => { if (some condition) { next() } try { const results = await axios.get(`https://a-domain.com/url/path`); const info = results.data; c ...

Updating the state of a nested array using React Hooks

After spending some time working with React Hooks, my main struggle has been dealing with arrays. Currently, I am developing a registration form for teams. Each team consists of a list of players (an array of strings). The goal is to allow users to add t ...

Having trouble receiving any ringing status in nextjs while utilizing the getstream SDK

I attempted to integrate the getstream video SDK for calling from the caller to the callee. While I can successfully create calls from the caller side, I am not receiving any status updates about the call on the callee side. Below are my codes for the cal ...

Variable revised is not accessible beyond the function

When making an ajax call, the value of received is supposed to be incremented by 1 on success. The issue arises when trying to check if received is less than 10 in order to prevent entering getMessage() unnecessarily. However, outside of the function, the ...

What is the method for retrieving the status of an xmlHttpRequest?

I'm curious about how to verify the status of an xmlHttp request once it has been sent. Can someone explain the process to me? Thank you. function sendRequest(){ //retrieve access token var accessToken = 'xxx'; //get user_id ...

Can a package-lock.json file be created without running an npm install command?

Is there a way to create only a package-lock.json file without having to redo the npm install process? I'm looking to generate the lock file without reinstalling any of the package files. Is this achievable? ...

Creating dynamic grids in React.js by utilizing HTML

Currently, I am tackling one of the projects on FCC which is the Game of Life. Prior to diving in, my focus is on figuring out how to render a grid on the page. I aim to modify the table dimensions while ensuring it fits neatly within its container. The ...

Whenever my NodeJs encounters an unhandledPromise, it throws an error

exports.createNewTour = async (request, response) => { try { const newlyCreatedTour = await Tour.create(request.body); res.status(201).json({ statusCode: "success", details: { toursData: newlyCreatedTour, }, ...

Running Python in React using the latest versions of Pyodide results in a malfunction

As someone who is new to React and Pyodide, I am exploring ways to incorporate OpenCV functionality into my code. Currently, I have a working piece of code that allows me to use numpy for calculations. However, Pyodide v0.18.1 does not support OpenCV. Fort ...

Express.js and Node version 0.10.29: The Mystery Post

Having trouble with sending JSON data to an express server and receiving 'undefined' for req.body.name. This is how the configuration is set up: const express = require('express'); const app = express(); app.configure(function(){ ...

Create a web application in NodeJS that mimics browser functionality by running JavaScript code from an HTML page

I'm a beginner in NodeJS and I am working on developing a web service that can send a response with the output of a JavaScript script from an HTML page sourced online. For instance: Imagine my webpage contains a JavaScript snippet that outputs "hell ...

Utilize React Material UI to dynamically update state with Slider interactions

Currently, I am in the process of developing a multi-step form (survey) using React.js and the Material-UI components library. However, I have encountered an issue with the slider component at one of the steps – it does not seem to update the state as ex ...

A JavaScript regular expression for identifying IMDB URLs

Could someone please help me identify the issue with this JavaScript code? "http://www.imdb.com/title/tt2618986/".match("~http://(?:.*\.|.*)imdb.com/(?:t|T)itle(?:\?|/)(..\d+)~i"); I tested it here https://regex101.com/r/yT7bG4/1 and it wo ...

When attempting to import the OrbitControls.js file, Three.js encounters an error and fails

I am completely new to javascript and unfamiliar with working with libraries. I am currently experimenting with basic three.js code, but unfortunately facing issues that I cannot seem to resolve. Following the documentation on Threejs.org, I have set up a ...

What is the reason behind Vue's decision not to cache method results?

Vue introduces the concept of Computed Properties that are only re-evaluated when their dependencies change. For example: computed: { foo() { return this.bar + this.baz; } } <div>{{ foo }}</div> This Computed Property recalculates onl ...

Leveraging ng-switch for template swapping

I'm currently facing an issue in my Angular app where I want to switch from a "sign in" form to a "sign up" form when the user clicks on the "Sign Up" button, but nothing happens upon clicking the button. The sign-in form persists on the screen withou ...

What is the best way to share dynamic content from a DIV or SPAN element on WhatsApp using jQuery?

I’ve been attempting to share the text content of a specific DIV on WhatsApp, but so far I haven't been successful. My goal is to only share a portion of the document (specifically the contents of showques). Below is the code snippet I've been ...

Mongoose: No documents are being returned by the .find() method

UPDATE : Similar question posted here: Trouble with Mongoose find() method I'm still new to working with nodejs and nosql databases. Today, I am building an API that retrieves data from my user collection which currently has two entries : The issue ...