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

streamlining form updates in vue

The code snippet provided is functional but unnecessarily complicated and lengthy. I am seeking a more efficient approach to achieve the desired outcome. <h6><label for="number">Change Number</label></h6> ...

Obtaining a byte array using the file input method

var profileImage = fileInputInByteArray; $.ajax({ url: 'abc.com/', type: 'POST', dataType: 'json', data: { // Other data ProfileImage: profileimage // Other data }, success: { } }) // Code in Web ...

Issue with accessing $index.$parent in function parameter within ng-repeat in AngularJS

Can anyone with more experience please explain to me why this particular code compiles successfully: <li class="btn dropdown top-stack breadcrumb-btn" ng-repeat="nodeName in selectedNodeNames"> <a class="dropdown-toggle btn-anchor"> ...

Transfer information from .gs (Google Apps Script) to a variable inside a <script> tag in an HTML document

[ {"id":1,"label":"Node 2"}, {"id":2,"label":"Node 3"}, {"id":3,"label":"Node 4"}, {"id":4,"label":"Node 5"} ] Hello there! The function getArray() in the code snippet above is returning the specified string ↑. I need help connecting this data w ...

Node Express for Advanced Routing

I'm currently developing a web application that will handle CRUD operations on an array within a collection. Here is the structure of the collection model: var mongoose = require('mongoose'); var website = require('./website'); ...

Resolving the Persistence Problem of Navigation Bar Fading In and Out

I've been struggling for hours trying different methods to achieve the desired outcome, but unfortunately, none of them have worked as expected. My goal is simple: I want the fixedbar to fade in when the scroll position exceeds the position of the ph ...

Protecting an API with passport-local authentication

Let me get right to the point. I've developed a secure application using passport-local, with all routes well-covered. The purpose of my app is to retrieve data from MongoDB and serve it as an API that feeds into d3 charts. While all my webpages are s ...

displaying a PDF file in Safari

Is there a way to display a PDF document within an HTML page without encountering a missing plugin error? I attempted to use the following code, but the error persists. Interestingly, if I drag the same PDF file directly into my browser, it displays perfe ...

Using JavaScript's setInterval function in conjunction with Math.random to obtain a random value

Just generated some random numbers. Wondering how to dynamically update the values of these numbers every 5 seconds with fluctuations less than +/- 5% compared to the current value. Need help using the setInterval function. Here is my code for Random Pric ...

"Having trouble with sound in react-native-sound while playing audio on an Android AVD? Discover the solution to fix this

react-native-sound I attempted to manually configure react-native-sound but I am unable to hear any sound. The file was loaded successfully. The audio is playing, but the volume is not audible on Android AVD with react-native-sound. ...

Transfer the information on the onClick event to the loop's function

When creating my component within the parent component, I follow this approach: renderRow(row){ var Buttons = new Array(this.props.w) for (var i = 0; i < this.props.w; i++) { var thisButton=<FieldButton handler={this.actionFunction} key={&ap ...

Having difficulty aligning ListItem to the right within a List

I am working with an array that contains objects which I need to display in ListItems of a List. My goal is to show these ListItems from the array Objects in a layout where odd numbers are on the left and even numbers are on the right. However, I am facing ...

Experimenting with JavaScript within an Immediately Invoked Function Expression

My team leader is requesting that I encapsulate my JavaScript code within an Immediately-Invoked Function Expression (IIFE). However, I am struggling to use spyOn in my Jasmine spec file. How can I properly use spyOn on the following: (function(){ fu ...

What is the importance of using a polyfill in Babel instead of automatically transpiling certain methods?

Recently, I have been diving into a course that delves into the use of babel in JavaScript. It was explained to me that babel, with the preset "env," is able to transpile newer versions of ES into ES5. However, I found myself facing a situation where the a ...

Using Rails to Pass Front-End JavaScript Data from an External API to the Controller

I need to retrieve coordinates from an external API, specifically the Google Maps API, and then send it to my controller. However, I am encountering a 500 internal server error when using jQuery/Ajax for this task. Researching the issue online suggests tha ...

The Bootstrap carousel controls now add the carousel ID to the address bar instead of just moving to the next slide

I can't figure out why my carousel isn't working. The id of the carousel is showing up in the webpage's address, which usually happens when the 'bootstrap.js' file is missing, but I have included it. Can anyone help me troubleshoo ...

Display or conceal nested divs within ng-repeat loop

I set up a div with sub divs to establish a nested grid system. There are three levels altogether: MainDiv - Always Visible SecondDiv - Display or conceal when MainDiv is clicked on ThirdDiv - Display or conceal when SecondDiv is clicked on <div c ...

Storing the output of asynchronous promises in an array using async/await technique

I am currently working on a script to tally elements in a JSON file. However, I am encountering difficulty in saving the results of promises into an array. Below is the async function responsible for counting the elements: async function countItems(direct ...

Can the CSS of an iframe be modified if the iframe is located on a different domain?

Is it feasible to modify the CSS of an iframe if the iframe is not located on the same domain? If so, what are some ways to apply and alter CSS for this situation? Any assistance would be greatly appreciated. <iframe id="frame1" width="100%" height="35 ...

How can I include inline CSS directly within a string instead of using an object?

Is there a way to write inline CSS in a string format instead of an object format? I attempted the following, but it did not work as expected: <div style={"color:red;font-weight:bold"}> Hello there </div> What is my reason for want ...