Linking input to radio buttons in Vue.js

When creating an edit form page, I encountered an issue where the page was not loading properly. Before the page loaded, I ran the following code:

beforeMount(){
    if(this.$route.meta.mode === 'edit'){
        this.initialize = '/api/artikel/edit/' + this.$route.params.id;
        this.store = '/api/artikel/update/' + this.$route.params.id;
        this.method = 'put';
    }
    this.fetchData();
},

In my fetchData() method, I retrieve corresponding data from the server based on the article id.

fetchData(){
    var vm = this
    axios.get(this.initialize)
        .then(function(response){
            Vue.set(vm.$data, 'form', response.data.form);
            Vue.set(vm.$data, 'rules', response.data.rules);
            Vue.set(vm.$data, 'option', response.data.option);
        })
        .catch(function(error){
        })
},

However, when binding the form data to radio buttons in my form, I noticed that it worked fine for input text but not for radio buttons as shown below:

<div class="form-group">
    <h5>Publish:</h5>
    <label class="radio-inline">
        <input type="radio" name="publish" class="styled" value="1" v-model="form.publish">
        Yes
    </label>
    <label class="radio-inline">
        <input type="radio" name="publish" class="styled" value="0" v-model="form.publish">
        No
    </label>
</div>

The radio button should be checked automatically based on the value from the database, but they were not being selected. However, manually clicking the radio buttons showed that the form.publish value changed accordingly in the Vue.js inspector in Chrome.

What could be causing this issue?

Answer №1

Perhaps the issue lies in how the value is being passed. Since you are assigning values of 0/1 to the radio button model, it requires a 0 or 1 value instead of true/false. Can you verify that this is the case?

Take a look at the snippet below and observe what happens when you switch 'true' to '1'

new Vue({
  el: '#app',
  data: {
    form: {}
  },
  methods: {
    update () {
      // does not work
      //var form = { publish: true } 
      // works
      var form = { publish: 1 } // <---- make sure it's 1 and not true?
      this.$set(this, 'form', form);
    }
  },
  
  mounted() {
    console.log(this.form)
    setTimeout(this.update, 1000)
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.8/vue.min.js"></script>

<div id="app">
  <div class="form-group">
      <h5>Publish:</h5>
      <label class="radio-inline">
          <input type="radio" name="publish" class="styled" value="1" v-model="form.publish">
          Yes
      </label>
      <label class="radio-inline">
          <input type="radio" name="publish" class="styled" value="0" v-model="form.publish">
          No
      </label>
  </div>
</div>

Answer №2

Oops, my mistake! The issue I was experiencing is not related to vue.js, but rather because I am utilizing uniform.js for styling my radio buttons in an admin template purchased from Themeforest. Unfortunately, the documentation provided is not very clear...

After doing some research, I discovered that uniform.js is responsible for styling my radiobuttons with JavaScript and CSS. I simply added a jQuery code to update the radiobutton functionality.

Answer №3

After spending a few hours troubleshooting, I realized that the reason my code wasn't working was because I had forgotten to include the

:checked="item.isActive == true"
property in my binding. Once I added this, everything worked perfectly.

                    <input
                      class="form-check-input"
                      type="radio"
                      name="students"
                      v-model="item.isActive"
                      :checked="item.isActive== 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

The process of incorporating types into Node.js and TypeScript for handling req and res objects

Check out the repository for my project at https://github.com/Shahidkhan0786/kharidLoapp Within the project, the @types folder contains a file named (express.d.ts) where I have added some types in response. The (express.d.ts) file within the @types folde ...

Setting the value for a HiddenField using jQuery in an ASP.NET application

Is there a way to set a value for a HiddenField control using jQuery? function DisplayContent(obj) { var FareValue = $(obj).closest('tr').find("[id*=lbFare]").text(); $(obj).parent().parent().find('[id*=pnlGrd]').show(); $ ...

Are there any downsides to utilizing the jQuery Load function?

I am in the process of creating a website that displays sensor data. I plan to incorporate a HighChart line chart to showcase this data. Since my website is relatively simple in terms of content, I have decided to consolidate all elements onto one page inc ...

Make sure to always send back JSON data when using the default error handler in ExpressJS

I'm in the process of developing an API server using ExpressJS. I want to guarantee that the server consistently delivers JSON data rather than HTML data. While I can easily make the server respond with JSON for all customized routes, I encounter diff ...

Safari Browser does not currently offer support for MediaRecorder functionality

[Log] Webcam permission error Error: MediaRecorder is not supported I am facing an issue while trying to record audio. The Chrome browser allows audio recording without any problem, but Safari is throwing an error. global.audioStream = await navigator.m ...

Using Vue.js 3 to fetch data from a REST API using the Axios

How do I properly retrieve and display an array using axios.get in Vue? The data is not showing up in my table cells when I use the v-for directive. Could the issue be related to the v-for statement? <tr v-for="params in form" :key=" ...

Sending data via req.body from middleware

One middleware function is defined as follows: app.use('api/', authenticate, bar); In the authenticate function, a variable is being attached to req.body like so: req.body.user = foo; However, when trying to access req.body.user inside the ba ...

Tips for removing ASP.NET MVC controller name from angular route

My ASP.NET MVC login page leads to a different page that is integrated with Angular. After logging in, the URL looks something like this: http://localhost:5083/Home#/home I want to remove the ASP MVC controller name ("Home") from the URL. Is there a ...

Adding clickable padding to a Draft.js editor can enhance the user experience and make the editing process

Is there a way to apply padding to the Draft.js Editor so that clicking on the padding area selects the Editor? If I add padding directly to the container div of the Editor, the padding displays properly but clicking on it does not enable writing in the E ...

Obtaining the Value of Input Text

Let's say you have the following HTML code: <form> Enter hash here: <input type="text" name="hash"> <button type="submit" formaction="/tasks/">Retrieve Url</button> </form> Is there a way ...

Is it possible that WebdriverIO is unable to retrieve the value for an input

Currently, I am in the process of automating tests specifically for a web application on Safari browser. However, I have encountered some challenges along the way. It appears that webdriverIO is not performing very well with Safari in my environment, which ...

What is the best way to store user input in local storage using Vue.js?

Following the official Vue.js site, I have been trying to implement Framework 7. However, when using an input field, [object InputEvent] is displayed both when typing text and attempting to save it. Is there a way to store a name in local storage and have ...

employ identical components in v-if and v-else

Currently, I am in the process of designing a login/register page using Vue. The layout includes separate tabs for both login and registration purposes. Here is a snippet of my template code: <transition v-bind:name="TabEffect"> <div ...

Simple steps for calling a lit component in React using the ScopedElementsMixin:1. Import

Looking to incorporate the web component Button (lit) into my project using a similar tag approach. For instance, if the <button-test> tag is present on the website, then it should be converted to <button-test-12345>. This is why ScopedElements ...

Performing a JavaScript/jQuery callback to server without the need for an accompanying executable backend

Today, a colleague in the tech world posed an interesting question to me: Can jQuery (or JavaScript in general) retrieve information about the filesystem from its source without the need for executable code? Initially, I instinctively responded by saying t ...

I have written code in JavaScript, but now I am interested in converting it to jQuery

What is the best way to convert this to jQuery? showDish("balkandish1") function showDish(dishName) { var i; $(".city").css('display', 'none'); $("#" + dishName).css('display', 'block'); } ...

Setting a default value in react-select

Recently, I developed a react-select component that is compatible with redux-form. The SelectInput component looks like this: const MySelect = props => ( <Select {...props} value={props.input.value} onChange={value => props.input.on ...

Troubleshooting Dynamic Input Issue - Incorrect Appending Behaviour - Image Attached

I am working on a project that involves adding input fields dynamically using JavaScript. However, I've encountered an issue where the styling of the first input field is not applied correctly when it is clicked for the first time. You can see the dif ...

React Login Redirect

I am struggling to implement a redirect in my React project login. Despite researching online and finding solutions using routers, I have been unsuccessful in adding it to my code correctly. Here is my code - how can I effectively implement the router? Ap ...

"Vue's prevention of default behavior in router-link element is effective in Chrome, but it seems to

My component uses a router-link as the root tag, and I'm trying to prevent its default link behavior in case there are issues with JavaScript or if it's disabled. In Chrome, I was able to achieve this using event modifiers like: @click.native.ca ...