Storing user input with AngularJS

I have a form below that I am trying to save. Please review my HTML code for the form.

HTML

<form ng-submit="save()">
    <input type="text" ng-model="user.name"/>
    <input type="text" ng-model="user.age"/>
    <input type="text" ng-model="user.homenumber"/>
    <input type="text" ng-model="user.road"/>
    <input type="text" ng-model="user.city"/>
    <input type="text" ng-model="user.school"/>
    <button type="submit">Save </button>
</form>

I used the following function to save the form data:

$scope.save = function (){
    console.log($scope.user)
}

The result after saving looks like this:

{ name:"dais",
  age:"24",
  "homenumber":"23",
  "road":"new road",
  "city":"colombo",
  school:"new school"
}

However, I need to save the form as a JSON object in the requested format:

Requested format:

{name:"dais",
 age:"24",
 "address":{
     "homenumber":"23",
     "road":"new road",
     "city":"colombo"
 },
 school:"new school"
}

Can someone help me modify my save function to achieve this?

Answer №1

To store address information, create an address object:

$scope.user = {};
$scope.user.address = {};

$scope.save = function () {
    console.log($scope.user);
}
<form ng-submit="save()">
    <input type="text" ng-model="user.name"/>
    <input type="text" ng-model="user.age"/>
    <input type="text" ng-model="user.address.homenumber"/>
    <input type="text" ng-model="user.address.road"/>
    <input type="text" ng-model="user.address.city"/>
    <input type="text" ng-model="user.school"/>
    <button type="submit">Save </button>
</form>

Answer №2

<input type="text" ng-model="user.homenumber"/>
<input type="text" ng-model="user.road"/>
<input type="text" ng-model="user.city"/>

Must use

<input type="text" ng-model="user.address.homenumber"/>
<input type="text" ng-model="user.address.road"/>
<input type="text" ng-model="user.address.city"/>

Answer №3

One way to structure your code is by creating a constructor function

function UserData(user){
  this.name = user.name;
  this.age = user.age;
  this.address ={homenumber : user.homenumber, road:user.road, city:user.city };
  this.school = user.school
}

You can then implement it in the following manner

 $scope.save = function (){
  let userDataToSave = new UserData($scope.user);
  console.log(userDataToSave);
}

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

Issue with h2 tag within JQuery's read more feature

How can I modify my jQuery code to wrap the middle text in an h2 tag? I am currently using a code snippet from code-tricks. You can find the original code snippets here: $(document).ready(function() { var showChar = 100; var ellipsestext = "..."; ...

Issue: [ng:areq] The function 'DepartmentCustomReportController' is missing and undefined in Internet Explorer

I am encountering an issue specifically in Internet Explorer, as the same controller works without any problems in Chrome. Here is a snippet of my index.html file: <script src="assets/js/boostrapJs/jquery-1.11.1.min.js"></script> <script s ...

The express app.get middleware seems to be malfunctioning due to a 'SyntaxError: Unexpected end of input'

Currently, I'm diving into an Express tutorial on YouTube but hit a roadblock with middleware that has left me bewildered. In my primary file, the code looks like this: const express = require('express'); const path = require('path&ap ...

Tips for retrieving and transferring the device key during social login with Cognito and AWS Amplify

I am working on integrating Cognito's setDeviceStatusRemembered function into the social login process, but I am facing an issue with the deviceKey parameter. The user object returned does not contain the required deviceKey. This project is built usi ...

Exclusively for Numerical Input with Number Keys

A customer on a website requires a Zip Code field that only accepts 5-digit numbers and triggers the numeric keypad on iOS and Android devices. It should also be compatible with external number pads on laptops. I've tried various approaches like keyC ...

Vue users are experiencing issues with the functionality of the Chart js plugin annotation

I've been attempting to include a horizontal line in my Chart.js using the annotations plugin, but it's not cooperating. My Chart.js version is 2.9.4, so I had to install it with the command: npm install [email protected] --save After inst ...

Retrieving the selected value from a Bootstrap dropdown using JavaScript when there are multiple dropdowns present

I have created multiple rows in javascript that are being rendered to the DOM from a Firestore collection. Each row contains a Bootstrap dropdown with the same select options (".a" elements). The id attribute of each row div is dynamically set based on the ...

Error: The function row.child.hasClass is not a recognized function

My challenge is creating row details for DataTables without using Ajax. I have implemented something like this: $(document).ready(function () { function format ( name, value ) { return '<div>Name: ' + name + '<br /> ...

Could there be a more efficient method to enable support for all video formats?

I have a case statement in my video validation function that checks for specific file extensions of video formats. However, I am wondering if there is a shorter way to write the code in order to allow all video formats instead of creating a long list of al ...

Using a jQuery gallery can cause links to become unresponsive and unclickable

While creating a responsive webpage with the Zurb Foundation framework, I encountered an issue when trying to incorporate nanoGallery which also uses jQuery. After adding the gallery scripts, the top menu generated by the Foundation script became unclickab ...

Struggling with mapping through a multidimensional array?

I'm facing an issue with using .map() on a nested array. I initially tried to iterate through my stored data using .map(), and then attempted another iteration within the first one to handle the nested array, but it didn't work as expected. The ...

The function chartobject-1.render() is returning an error message stating: "Unable to locate the specified container within the document. This issue is occurring in the

I've encountered an issue while trying to integrate FusionCharts into my Vue.js project. Every time I attempt to render the charts within my components, I consistently run into this error. Here's a snippet of one of the components: <template&g ...

Is there a way to remove CSS based on the generated HTML code?

Currently tackling a project in Next.js involving custom SCSS, Bootstrap SCSS, and React-Bootstrap. Struggling with the bloated size of our main.scss file due to unused CSS. After observing that 95% of the CSS is not utilized, I aim to eliminate all unnec ...

Updating the state of an object nested within another object in React JS

So, I have a nested object within another object and I need to update the state of one or more properties in the inner object. This is my current state: const [products, setProducts] = useState({ name: '', type: '', price: '& ...

Count of elements in one flexbox row

Having a flexbox container with multiple items in row-wrap format, is there a way to use JavaScript to determine the number of items in each row? Essentially, finding out at what point they wrap. For instance- <div class="container"> <div clas ...

Is there a way to link two HTML files containing jQuery within an HTML index file?

I'm currently working on creating an index page for a pair of HTML files that utilize jquery. Let's break down the structure of these files: Emps1, Emps2: These are two HTML tables that start off empty. TabA_stats, TabB_stats: Each HTML file ha ...

Session storage conditional statement is not behaving as anticipated in JavaScript

I am currently working on session storage functionality where a user must select one radio button on the first page and then click the next button. On the second page, a div is supposed to show up. On the first page, I have created a function with a set of ...

What is the process for assigning a random string value to each document within a mongodb collection using the mongo shell?

Looking to assign a randomly generated string property to every item in a MongoDB collection. Planning to leverage the mongo shell and the updateMany function for a swift and efficient solution. ...

What is the best way to sort through an array depending on a specific sequence of elements provided

I am trying to create a custom pipe in Angular 5 that filters an array of events based on a given sequence. For instance, if my data is: ["submit", "click", "go_back", "click",...] I want to filter this data based on up to three inputs. If input ...

Obtaining values from multi-dimensional arrays with JavaScript and node.js

I have a data structure like this: let arr = [ ['animal','lion'], ['plant','rose'], ['tree','coconut'], ] I want to reformat it to look like this: ['animal','lion' ...