Why is my v-model not being updated when using a radio button in Vue.js?

After reviewing the documentation, I attempted to implement the code provided. While I am able to successfully retrieve data for enquiryDesc, I am consistently getting a value of 5 for the rating field. I even experimented with changing the radio group to a checkbox, but unfortunately, it did not yield the desired outcome.

This is how my html form looks:

<form id="enquiryBox" method="POST" data-parsley-validate="true" v-on:submit.prevent="handelSubmit()">
  <div class="modal-body brbottom-20">
    <div class="clearfix">
      <div class="col-lg-6">
        <div class="form-group required">
      <fieldset class="rating">
                <input v-model="rating" type="radio" id="rating" name="rating" value="5" ><label class = "full" for="star5" title="Awesome">5</label>
                <input v-model="rating" type="radio" id="rating" name="rating" value="4" ><label class="half" for="star4half" title="Pretty good">4</label>
    </fieldset>
        </div>
      </div>
      <div class="col-lg-6">
        <div class="form-group required">
          <label>Enquiry</label>
          <textarea placeholder="Write your enquiry here" rows="7" id="enquiryDesc" name="enquiryDesc" class="form-control required" title="Desc" v-model="enquiryDesc" required="required"></textarea>
        </div>
      </div>
    </div>
  </div>
  <div class="">
    <button id="btn-submit-enquiry" class="btn whiteButton" type="submit">Post Enquiry</button>
  </div>
</form>

This is the Vue.js script I am utilizing:

enquiryBox = new Vue({
   el: "#enquiryBox",
   data: {
     rating: '',
     enquiryDesc: '',
   },
   methods: {
     handelSubmit: function(e) {
       var vm = this;
       data = {};
       data['rating'] = this.rating;
       data['enquiryDesc'] = this.enquiryDesc;
       console.log(data);

       $.ajax({
         url: 'https://api/post/add_review/',
         data: data,
         type: "POST",
         dataType: 'json',
         success: function(e) {
           if (e.status) {
             alert("Success")

           } else {
             vm.response = e;

             alert(" Failed")
           }
         }
       });
       return false;
     }
   },
 });

Upon inspecting the response from the console.log(data)

{rating: "", enquiryDesc: "hello how are you"}

Despite my efforts, the rating value remains 5 and does not reflect any changes.

Answer №1

It is not necessary to bind the value to the radio buttons since they do not need to be modified. Instead of using v-bind:value="5" and v-bind:value="4", simply use value="4" and value="5".

In the data section, you can remove setting rating: 5 and just use rating: ''. The user will select a rating and then the data will be filled automatically.

Take a look at this code snippet.

enquiryBox = new Vue({
   el: "#enquiryBox",
   data: {
     rating: '',
     enquiryDesc: '',
   },
   methods: {
     handelSubmit: function(e) {
       var vm = this;
       data = {};
       data['rating'] = this.rating;
       data['enquiryDesc'] = this.enquiryDesc;
       console.log(data);

       
       return false;
     }
   },
 });
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>VueJS</title>
    <script  src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.0.3/vue.js"></script>
</head>
<body>
    
        <form id="enquiryBox" method="POST" data-parsley-validate="true" v-on:submit.prevent="handelSubmit()">
  <div class="modal-body brbottom-20">
    <div class="clearfix">
      <div class="col-lg-6">
        <div class="form-group required">
      <fieldset class="rating">
                <input v-model="rating" type="radio" id="rating" name="rating" value="5" ><label class = "full" for="star5" title="Awesome">5</label>
                <input v-model="rating" type="radio" id="rating" name="rating" value="4" ><label class="half" for="star4half" title="Pretty good">4</label>
    </fieldset>
        </div>
      </div>
      <div class="col-lg-6">
        <div class="form-group required">
          <label>Enquiry</label>
          <textarea placeholder="Write your enquiry here" rows="7" id="enquiryDesc" name="enquiryDesc" class="form-control required" title="Desc" v-model="enquiryDesc" required="required"></textarea>
        </div>
      </div>
    </div>
  </div>
  <div class="">
    <button id="btn-submit-enquiry" class="btn whiteButton" type="submit">Post Enquiry</button>
  </div>
</form>    


</body>

</html>

Alternatively, you can click on a number and then press submit to see the updated result:

var enquiryBox = new Vue({
   el: "#enquiryBox",
   data: {
     rating: '',
     enquiryDesc: '',
   },
   methods: {
     handelSubmit: function(e) {
       var vm = this;
       data = {};
       data['rating'] = this.rating;
       data['enquiryDesc'] = this.enquiryDesc;
       console.log(data);       
       return false;
     }
   },
 });
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>VueJS</title>
    <script  src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.0.3/vue.js"></script>
</head>
<body>
    <div id="enquiryBox">
        <form method="POST" data-parsley-validate="true" v-on:submit.prevent="handelSubmit()">
          <div class="modal-body brbottom-20">
            <div class="clearfix">
              <div class="col-lg-6">
                <div class="form-group required">
                  <fieldset class="rating">
                    <span @click="rating = 1">1</span>
                    <span @click="rating = 2">2</span>
                    <span @click="rating = 3">3</span>
                  </fieldset>
                </div>
              </div>
              
            </div>
          </div>
          <div class="">
            <button id="btn-submit-enquiry" class="btn whiteButton" type="submit">Post Enquiry</button>
          </div>
        </form>
    </div>


</body>

</html>

Answer №2

I encountered a comparable problem! I managed to solve it by utilizing the :value attribute and the @change event.

 <input :value="rating" @change="rating=$event" type="radio" id="rating" name="rating" value="5">
        

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

Updating React Native using setState is not possible

In my React Native application, there is a function that deletes an item: delete(index){ this.setState({deletedIndex:index, cachedCart:this.state.Cart, Cart: this.state.Cart.splice(index,1) }, function(){ console.log(th ...

Is there ample documentation available for Asp.Net Ajax controls?

Struggling to locate the client side functionality of Asp.net Ajax controls such as calendarextender. How can I determine the specific client side functionalities of each control or Calendar control? So far, I have only discovered the properties ._selected ...

Steps to clear the form in vue after the ajax request has been successfully submitted

Exploring Vue.js Web Form Validation with a Scenario If you are interested in the vue-form validator library, it can be found at https://github.com/fergaldoyle/vue-form For a demonstration of this scenario, check out the following jsfiddle link: https:/ ...

Guide on generating a route using coordinates in a threejs environment

Currently, I am working with an array of coordinates obtained from the Google Maps Navigation API. I have successfully plotted these coordinates on a sphere, however, my objective is to extract the shape of the path by combining all the coordinate points ...

What is the best way to access a key from an object within the map function?

What is the method to extract the key from an object in ReactJS? {this.state.data.map((object, index) => ( <div>{Object.keys(object)}</div> ))} For example, if this.state.data contains: [{mykey1:23},{mykey2:24},{mykey3:34}] T ...

Creating experiences for websites controlled by gestures

It's been a great experience working on a website that utilizes gesture-based technology. My inspiration for this project came from various sources, including this link. Despite researching extensively through websites, Google, Wikipedia, and GitHub, ...

Getting your JS project off the ground with NPM!

I am looking to develop a vanilla JavaScript project that utilizes npm packages, but I want to do it without using bundlers like Webpack. Here is a basic structure: index.html: <div id="app"></div> <script src="./index.js" type="module"&g ...

Using `href="#"` may not function as expected when it is generated by a PHP AJAX function

I am facing an issue with loading html content into a div after the page has loaded using an ajax call. The setup involves a php function fetching data from the database and echoing it as html code to be placed inside the specified div. Here is my current ...

Insufficient Resources Error (net::ERR_INSUFFICIENT_RESOURCES) encountered while executing jQuery script with multiple ajax requests for 2 minutes

Upon initially loading the code below, everything seems to be functioning smoothly with the dayofweek and hourofday functions. However, shortly thereafter, the browser (Chrome) freezes up and displays the error message: net::ERR_INSUFFICIENT_RESOURCES. Thi ...

Having trouble making the swing effect trigger on mouseover but not on page load

I am trying to achieve a swinging effect on mouseover only, not on page load. Below is the JS code I have: (function swing() { var ang = 20, dAng = 10, ddAng = .5, dir = 1, box = document.getElementById("box"); (function setAng(ang){ ...

After employing a combination of forEach and filter queries in JavaScript to sift through dropdown options, no results are being generated

Hey there fellow developers, I'm currently in the process of developing an app and have reached the stage where I am filtering elements using dropdowns. I am querying a JSON object and comparing it with the selected element in the dropdown at that mom ...

Enhance Your jQuery Experience with Advanced Option Customization

I am currently developing a plugin that deals with settings variables that can be quite deep, sometimes reaching 3-4 levels. Following the common jQuery Plugin pattern, I have implemented a simple method for users to update settings on the go using the not ...

Organizing classes under namespaces in Node.js

Currently working on a project in node.js. I have several related classes that I want to organize in a subdirectory, with one class per file structured like this: lib/ main.js melons/ casaba.js cantaloupe.js carnegie.js I plan to us ...

"Excessive label length on yAxis causing display issues in chart with chartJs

I'm facing an issue with excessively long labels on the Y-axis while using the "chartjs" and "vuejs" modules. To provide a visual representation of the problem, I have attached an image: View Image Here Below is the snippet of my code where the prob ...

Remove an item from an array in nuxtjs

Whenever I attempt to remove an element from an array, I encounter a peculiar issue. After making three posts and attempting to delete them, the last remaining post is often one that has already been deleted - until I refresh the page. <tr class="b ...

Having trouble finding a solution to prevent code from automatically adding a class in jQuery/JavaScript?

I am currently in the process of customizing the FlexNav Plugin. I have made a modification to allow sub-menus to open on click instead of hover. However, a new issue has arisen where it requires two clicks to open a submenu. Upon investigation, I have i ...

Refresh the Dom following an Ajax request (issue with .on input not functioning)

I have multiple text inputs that are generated dynamically via a MySQL query. On the bottom of my page, I have some Javascript code that needed to be triggered using window.load instead of document.ready because the latter was not functioning properly. & ...

Transforming functions with dependencies into asynchronous operations with the help of promises

Can I convert both of my functions into asynchronous functions, even though one function relies on the other? Is it feasible for function b to execute only after function a? ...

Using Paper.js to access and manipulate document.body.style.opacity within a paperscript

My website is essentially one large canvas image. Currently, the body fades in when loaded using this code: <body onLoad="document.body.style.opacity='1'"> However, I want to initiate this fade within my paperscript because sometimes the ...

Patience is key when awaiting the completion of several promises

I am currently utilizing the SQLStorage feature provided by the Ionic platform. The remove function within this tool returns a promise. Within my code, I have a need to remove multiple values and then execute some additional code once all removals are comp ...