Connect my Vue.js model data to the object that will be used for submission

I need help figuring out how to bind data from my input field into my Vue.js model. I've tried putting the UnitName inside the model but it's not working. Can someone provide some guidance on how to achieve this?

  new Vue({
  el: "#app",
  data: {
  UnitName:'',
  },
  methods: {
    toggle: function(todo){
        todo.done = !todo.done
    }
  }
})

$( document ).ready(function() {
 $("#myMagic").click(function(){
alert("test");
$.ajax({
  url: "",
  type: "POST",
  data: {
    "UnitName": "bobby",

  },
  headers: {
     "content-type": "application/x-www-form-urlencoded"
  },


  })
  
})

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.1/css/all.min.css">

        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">

        <script src="https://s.brightspace.com/lib/jquery/2.2.4/jquery.min.js" role="presentation"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>


<body>
<div id="app" class="container">



                Title <input v-model="UnitName">{{UnitName}}<br><br>
   

<button class="btn btn-primary" id="myMagic">Create</button>

</div>

Answer №1

In order for your data to work properly, it needs to be structured as a function that returns an object. You then have to bind the onclick event of your button. Don't forget to use preventDefault to stop the form from reloading the page.

new Vue({
  el: "#app",
  data(){
  return {
    UnitName:''
    }
  },
  methods: {
    toggle: function(todo){
        todo.done = !todo.done
    },
    onSubmit(event){
      event.preventDefault();
      alert(this.UnitName);
      $.ajax({
        url: "",
        type: "POST",
        data: {
          "UnitName": this.UnitName,

        },
        headers: {
           "content-type": "application/x-www-form-urlencoded"
        }
      })
    }
  }  
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.1/css/all.min.css">

        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">

        <script src="https://s.brightspace.com/lib/jquery/2.2.4/jquery.min.js" role="presentation"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>


<body>
<div id="app" class="container">



                Title <input v-model="UnitName">{{UnitName}}<br><br>
   

<button class="btn btn-primary" id="myMagic" @click="onSubmit">Create</button>

</div>

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

Choose a single asset from the list of values stored in the Map

I'm looking to implement something similar to the following: let myMap = new Map<string, any>(); myMap.set("aaa", {a: 1, b: 2, c:3}); myMap.set("bbb", {a: 1, b: 2, c:6}); myMap.set("ccc", {a: 1, b: 2, c:9}); let cs = myMap.values().map(x => ...

PHP form headaches: issues with submitting and posting

I'm having trouble with the submit button in my PHP code. Here's what I have so far (it's for a website where users can rate things): <form method="POST> <input type="radio" name="person" value="1" /> <input type="radio" name ...

implementing autocomplete feature with array data in vue js

I have successfully implemented my code to display all the results in a typeahead field. However, I am facing an issue where some data is missing. How can I merge all the data into one array? data() { return { list: [], } } axios.get(&apo ...

Generate a structured table display using the JSON information

How can I convert the following JSON data into a tabular view? {"data_report":[{"data":[1,2,0,3],"label":"Test1","backgroundColor":"blue"}, {"data":[3,4,2,5],"label":"test2","backgroundColor":"#a3eaae"}, {"data":[2,3,1,4],"label":" ...

Executing a JavaScript function through C# code

Does anyone have a code snippet for calling a JavaScript function from C#? Here's the scenario: I have an ASP.NET page with an ASP button. When this button is clicked, I want to call a JavaScript function. For example: In my ASP.NET page, <but ...

Sorting a function with two parameters in descending order is possible even when dealing with an empty array and no initial value for reduction

My npm test is not passing the third out of six tests. I have attempted to sort it using the following code snippet: sumAll.sort(function(min,max)) { return max - min; } However, this approach did not work. I also tried incorporating conditionals in t ...

What is the best way to incorporate custom KnockoutJS functions using RequireJS?

I am facing an issue with my View Model that utilizes a custom observableArray function for sorting. The error message I receive states: "...has no methods 'sortByProperty'". How do I go about loading the handlers.js file to resolve this problem ...

Issues with the webpack-dev-server and React

I was just reading up on Webpack and the moment came for me to start using it, but I ran into an error. npm ERR! code ELIFECYCLE npm ERR! errno 1 npm ERR! <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6a09180b471e1f1e ...

Tips for adjusting column sizes in ag-grid

I'm a beginner with ag-grid and need some help. In the screenshot provided, I have 4 columns initially. However, once I remove column 3 (test3), there is empty space on the right indicating that a column is missing. How can I make sure that when a col ...

Server Receiving Missing Post Parameters

I've developed a straightforward $resource factory. .factory('Order', order) order.$inject = ['$resource', "ApiEndpoint", "UserRecord"]; function order($resource, ApiEndpoint, UserRecord) { return $resource(ApiEndpoint.url + & ...

The Echo join function is unable to receive data from a broadcasted presence channel

I'm currently grappling with laravel's echo and pusher functionalities, encountering obstacles despite consulting the documentation and various tutorials. My aim is to implement a real-time chat messaging feature on my website, following along wi ...

How to display content in separate divs using jQuery hover functionality

I'm in the process of creating my online portfolio by using bootstrap and jquery. I have a series of images arranged side by side with each other, and I want to make the description for each image appear when that specific image is hovered over. Each ...

Having trouble importing ES modules using the "node" command in my Nuxt project

Within my nuxt project, I have utilized serverMiddleware defined in nuxt.config.js like so: serverMiddleware: ['~/api'] All the files located in the api directory are equipped with import and export statements and they function flawlessly when ex ...

Filter an array using an algorithm inspired by Binary Search Trees

I am facing a challenge with a sorted array of dates, here is an example: let arr = ['2019-03-12', '2019-02-11', '2019-02-09', '2018-06-09', '2018-01-24', ..] The arr has a length of 100,000, and I need t ...

Having trouble with setting up ENV variables while deploying the app on Heroku

I recently deployed my node.js app to Heroku, and I'm facing some issues with its functionality. The app loads fine, but when I try to sign in, it breaks down. It seems like the environment variables are not loading correctly, specifically the db vari ...

Converting Laravel variable into an image using JavaScript

I have a base64 string that I'm passing from the controller to the view. After verifying that the base64 string is correct online (by converting it to an image), I am attempting to call it in my JavaScript like so: <script> var crosshairImg ...

Update the jQuery Get function to enable asynchronous behavior

I've recently been tasked with updating some older code to be asynchronous. The code in question is a jQuery GET function that looks like this: jQuery.get("my url", function(data){ //code here }); What steps can I take to convert this to an as ...

Applying the Directive/Isolated Scope as Embedded HTML within an Angular-Bootstrap Popover

If you're using the angular-ui popover, you have the ability to include HTML content within it. However, I encountered some difficulties in placing a directive called sampleDirective inside the popover. Despite my attempts with the $sce.trustAsHtml an ...

Clickable div containing a hyperlink

I need assistance with a clickable div that contains a link. Here is the setup: HTML: <div onClick="goToCat(2);" class="author-topics-block "> <a href="http://mywebsite/page/?cat=2">The woman in steel</a> </div> CSS: .author ...

Error message in Typescript: When a class has initialized properties, a 'super' call must be the first statement in the constructor

I am currently facing some typescript errors in my project. Would you like to see a sample of the code that is causing the issue? Here is a snippet: module CoreWeb { export class Controller implements IController { public $q; ... This piece of cod ...