Navigating JSON data to retrieve a specific property in AngularJS using a select form

Struggling with AngularJS and JSON. I have a form.html view where users can select their province. I have a Province JSON file for the select tag, but when storing in MySQL, I need the province Id. I tried using ng-value="province.id" in the option tag but it didn't work. How can I retrieve the pid (provinceId) at the same time the user selects a province?

province.JSON

[
    {
    "pid" : 1,
    "name" : "Ontario"
    },
    {
    "pid" : 2,
    "name" : "Québec"
    },
    {
    "pid" : 3,
    "name" : "Nova Scotia"
    },
    {
    "pid" : 4,
    "name" : "New Brunswick"
    },
     ...

form.html

<select name="province" ng-model="user.province" ng-required="true"> 
 <option value="">--- Please select ---</option> 
 <option ng-repeat="province in provinces">{{province.name}}</option>
</select>

controllers.js

$scope.submitForm = function (user) {              
    dataObj = {
        "name": user.name,           //it works and all fine
        "province": user.province,   //it works and all fine
        "telephone": user.telephone, //it works and all fine
        "postalcode": user.postalcode, //it works and all fine
        "salary": user.salary,         //it works and all fine
        "provinceId" : user.pid       // undefined .. 
    }

Answer №1

Give this a try:

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
    $scope.user = {};
    $scope.provinces = [{
                        "pid" : 1,
                        "name" : "Ontario"
                        },
                        {
                        "pid" : 2,
                        "name" : "Québec"
                        },
                        {
                        "pid" : 3,
                        "name" : "Nova Scotia"
                        },
                        {
                        "pid" : 4,
                        "name" : "New Brunswick"
                        }
                      ];
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
 <select name="contactCountry" ng-model="user.province" ng-options="item.pid as item.name for item in provinces" ><option value="">Select provinces</option>
 </select> 
 <br>
 <p>Selected Province Id = {{user.province}}</p>
</div>

Hopefully, this solution works for you.

Answer №2

When the user submits, the select tag will be stored as an object like {"pid:1", "name":"Ontario"}, allowing me to fetch it in my controller.

The key here is to structure it as an object.

HTML File

<select name="province" ng-model="user.province" ng-options="item.name for item in provinces" class="form-control input-lg" ng-required="true"> 
    <option value="">Select provinces</option>
<select>

Controllers.js

myFactory.set(user);                 
dataObj = {
    "name": user.name, 
    "province": user.province.name,   
    "telephone": user.telephone,
    "postalcode": user.postalcode, 
    "salary": user.salary,
    "pid" : user.province.pid
}

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

Sending an image from a NodeJS socket server to another server: The ultimate guide

Hello there, I'm currently working on a new project and I could really use your input on a challenge I'm dealing with. Here's the situation: I have a web server running a socket.io module. The server is listening on port 3012 and streaming ...

What are the steps to extract information from an observable?

Having trouble retrieving data from a request? I've encountered an issue where the data retrieved inside .subscribe in an observable function is returning as undefined when trying to access it outside the function. It's quite frustrating! Here i ...

What are the steps to caching a message using discord.js?

In order to create a Discord bot with a command !edit [id] [new content], I have implemented the following code: if (MessageContent.startsWith('!edit ')) { if (authority >= 3) { //if false if (args.length < 3) { ...

Ensuring consistent placement and scrollability of two divs across all screen sizes

I am in need of a solution to fix the top and bottom divs in the given image. The scroll should only occur when there is overflow. <!DOCTYPE html> <html> <head> <script src="//code.jquery.com/jquery-1.9.1.min.js"></script> ...

Confidently set up a proxy that is recursively nested and strongly typed

I have a collection of objects where I store various content for a user interface. Here is an example: const copy = { header: { content: 'Page Header' }, main: { header: { content: 'Content Subheader' }, body ...

Executing AJAX POST request with callback function

I successfully used this code for the get function to retrieve data. It works flawlessly and I am able to fetch the required data using this function. function getdata(getdatafrom, resultclass){ $.get(getdatafrom, function(data) { $(result ...

Execute a script upon page load

Is there a way to trigger a script tag <script> immediately upon the website loading? I've experimented with various codes, but haven't found one that meets my needs. ...

Utilizing Node.js for Gmail API: Extracting Inline/Embedded Images

When working with email data, one approach is to use the gmail.users.messages.get() method. After fetching the email data, there are two functions used to handle the payload. function getBody(message) { var encodedBody = ''; try{ i ...

I am experiencing an issue with my d3 force directed graph where the links are not

I am relatively new to d3 and have limited experience with web frontend development. In my current web application project, I am attempting to create a force directed graph. Despite spending several hours trying to make it work, I have been unable to displ ...

Extracting data from a JSON subarray and injecting it into a template using Backbone

Need help with Backbone: newbie here! I'm trying to extract items from a JSON subarray and insert them into a specific location on my template. I'm having trouble figuring out how to target those specific items. The JSON subarray in question is ...

Is there a way to transition an element from a fixed layout position to an absolute layout position through animation?

I am looking to create a dynamic animation effect for a button within a form. The goal is for the button to move to the center of the form, while simultaneously undergoing a horizontal flip using a scale transform. During the midpoint of this animation, I ...

Conceal portion in HTML until revealed

I am attempting to create 3 sections within a single HTML file using the <section id="id"> tag, and I want to be able to open each section by clicking a link in the header with <a href="#id">1</a>, and then close it when another section i ...

Conceal the heading 4 element when a specific text is searched

I have a search script that filters the text, but I want to hide the h4 element at the top of each ol. How can I achieve this? The issue I'm facing is that while the text gets filtered correctly, the h4 element (which should be hidden) remains visibl ...

Patience is key when it comes to waiting for a function to finish before moving on to the next step

I'm delving into the world of node js and currently immersing myself in the concepts of promises and async/await. Here's a code snippet I've been experimenting with, but I can't quite figure out how to ensure that the code waits until t ...

Can you identify the issue in this code?

I am facing an issue with using this code to save values in a table when the page loads. The function that searches for values is written in PHP, and I need to use these values in my script. Unfortunately, the current approach I am trying doesn’t seem ...

CSS Text ellipsis displays only the beginning of each paragraph

I want to add ellipsis to a text, but it keeps including the first line of all paragraphs. What I actually need is for only the first line of the content to have the ellipsis applied. Here is an example of the content: When using websocket to send message ...

Encountering an Enumeration Exception when trying to delete an element from a collection list using a foreach loop

I encountered an issue when attempting to remove an element from a list collection using foreach. I have searched online but have not found a clear explanation for the problem. If anyone has knowledge about this, please share the information. ...

Using Axios in a VUE application to handle response data

I've been working on a VUE application and I'm currently exploring how to handle post responses with Axios. Initially, I used vue-router for fetching data but decided to give Axios a try. Axios code: methods: { sendForm () { ...

While iterating through the material-ui rating component, the 'index' value remains constant at 0 within the 'onChange' function

For my e-commerce React.js web app, I want to show the rating value of each product. Using the JS map function, I was able to track which product was hovered by its index ('onChangeActive' is the handler for this). {products.map((product, index) ...

Tips for executing a loop while waiting for a jQuery ajax request to complete

I currently have this code setup: for (var i = 0; i < $total_files; i++) { $.ajax({ type: 'POST', url: 'uploading.php', context: $(this), dataType: 'json', cache: false, contentType: false, pr ...