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

A mistake has occurred: Unhandled promise rejection TypeError: Unable to assign the property 'devices' to an undefined object in Ionic 4 with Angular

Within my MyDevicesPage class, I am attempting to manipulate the res object and then pass it to the updateDevicesToServer method of DataService for further actions. The code compiles without errors, but at runtime, an error is thrown: ERROR Error: Uncaught ...

Transmitting a JavaScript file via a Node.js server

I have a NodeJS server that sends a JavaScript file to the client. However, the JavaScript file does not import the libraries it needs on the client side. I load these libraries on the client side before receiving the file. Why is the file unable to find t ...

Import components on the fly

In my Home.vue component, I am attempting to dynamically import components. The Vue component structure is as follows: <template> <div> <!-- NEW --> <div v-for="widget in widgets"> <component v-b ...

Utilize Javascript to convert centimeters into inches

Can anyone help me with a JavaScript function that accurately converts CM to IN? I've been using the code below: function toFeet(n) { var realFeet = ((n*0.393700) / 12); var feet = Math.floor(realFeet); var inches = Math.round(10*((realFeet ...

The cloned rows created with jQuery are failing to submit via the post method

Hello, I am currently working on a project in Django and could use some assistance with my JavaScript code. Specifically, I am trying to incorporate a button that adds new rows of inputs. The button does function properly as it clones the previous row usin ...

Contrasting images showcasing Headless vs Non Headless settings in Puppeteer

I'm currently attempting to capture a screenshot or PDF of the content available at this URL. When using the option {headless: false}, the screenshot is generated correctly; however, in headless mode, some images do not render in the screenshot (for e ...

I am experiencing difficulty running Vue.js projects that I downloaded in Visual Studio Code and keep encountering the following error message: ERR! For a detailed log of this issue, please refer to:

After restarting my computer and reinstalling everything, I encountered an issue. I can create a Vue project without any problems and run it using the npm run serve command. However, when I try to run the projects that I have archived, I receive the follow ...

"Embrace the power of Ajax and JSON with no regrets

function register() { hideshow('loading', 1); //error(0); $.ajax({ type: 'POST', dataType: 'json', url: 'submit.php', data: $('#regForm').serialize(), su ...

Manipulate data in petite-vue beyond the application's scope

My exploration led me to petite-vue for its compact size and straightforward approach, perfect for my basic UI update needs on a webpage. I want to manage the visibility of DOM elements along with controlling class names and styles. With multiple JavaScri ...

Can we use classlist for adding or removing in Angular 2?

One of the features in my project is a directive that allows drag and drop functionality for elements. While dragging an element, I am applying classes to both the dragged element and the ones it's being dragged over. This is how I currently handle it ...

What could be causing the "Error - Only secure origins are permitted" message to appear for my service worker?

Whenever I attempt to implement a service worker on my progressive web application page, why does the browser console display this specific error message? ERROR "Uncaught (in promise) DOMException: Only secure origins are allowed JavaScript Code: ...

Examining the words within strings and drawing comparisons

I am attempting to analyze words within strings for comparison purposes. This is my objective: var string1 = "Action, Adventure, Comedy"; var string2 = "Action Horror"; if (string1 contains a word from string 2 == true) { alert("found!"); } I have e ...

What methods does MaterialUI utilize to achieve this?

Have you checked out the autocomplete feature in their component? You can find it here: https://mui.com/material-ui/react-autocomplete/ I noticed that after clicking on a suggestion in the dropdown, the input box retains its focus. How do they achieve thi ...

Troubleshooting Cordova's ng-route functionality issue

I am currently working on an Angular application that includes the following code: // app.js var rippleApp = angular.module('rippleApp', ['ngRoute', 'ngAnimate', 'ngAria', 'ngMaterial']); // configure ou ...

The utilization of the "notFound" prop within getStaticProps does not influence the HTTP status code returned by the page

I recently set up a fresh Next.js application and created the following page: // /pages/articles/[slug].js import React from 'react' import { useRouter } from 'next/router' import ErrorPage from 'next/error' const Article = ...

Having trouble accessing the root route in production environment

After creating a basic Node application with 5 routes that serve different HTML documents, I encountered an issue. While all the routes function properly when running on localhost, in production my root route displays a 404 error page, indicating that the ...

Expand the accordion to reveal all the content

I'm facing an issue with my accordion where a scrollbar appears in every content section. To fix this, I tried setting overflow: hidden in the CSS: .ui-accordion .ui-accordion-content { padding: 1em 2.2em; border-top: 0; overflow: hidd ...

Connecting to deeply nested attributes within an object using specified criteria

I apologize if the title of my query is not very descriptive, I couldn't come up with a better one. Please feel free to suggest improvements. I am currently working on developing a reusable "property grid" in Angular. My goal is to create a grid wher ...

Storing Json data in a variable within Angular 2: a step-by-step guide

Within the params.value object, there are 3 arrays containing names that I need to extract and store in a variable. I attempted to use a ForEach loop for this purpose, but encountered an issue. Can you spot what's wrong? var roles = params.forEach(x ...

Exploring the use of the "++" operator in Regular

Is there a way to detect the presence of ++, --, // or ** signs in a string? Any help would be greatly appreciated. var str = document.getElementById('screen').innerHTML; var res = str.substring(0, str.length); var patt1 = ++,--,//,**; var resul ...