How can I specify the array's length when using JSON.stringify in AngularJS?

I am looking to store form values in JSON to send via $http.post. One of the values, rooms, should be an array with a length determined by the selected value from md-select. The value of Adult should be included within each room entry.

var data = {
rooms: [{
    adults: this.adultsHotels,
  }]

This is how my rooms should appear in the view:

<md-select ng-model="rooms" name="numberOfRooms" ng-required="true">
  <md-option ng-repeat="roomsHotel in roomsHotel"
             ng-model="roomsHotel"
             ng-selected = "$first"
             ng-value="roomsHotel.number"
             ng-messages>
            {{roomsHotel.number}}
  </md-option>
</md-select>

The controller for rooms is as follows:

$scope.roomsHotel = ('1 2 3 4 5').split(' ').map(function(roomsHotel) {
    return {number: roomsHotel};
  });

The view for selecting number of adults is shown below:

<md-select ng-model="adultsHotels" name="numberOfAdults" ng-required="true">
    <md-option ng-repeat="adultsHotel in adultsHotel"
               ng-model="adultsHotel"
               value="{{adultsHotel.number}}"
               ng-messages>
                {{adultsHotel.number}}      
    </md-option>
</md-select>

Note: The objective is to dynamically add rooms based on selection and specify the number of adults in each. Appreciate any assistance.

 "rooms": [
    {
        "adults": "1"
    },
    {
        "adults": "2"
    }
]

Answer №1

After reviewing your code on the provided plunker, it seems that you can make some modifications to your script file by adding the following code:

// Updated code snippet

var app = angular.module('app', ["ngMaterial"]);

app.controller('myCtrl', function($scope) {
  $scope.roomsHotel = ('1 2 3 4 5').split(' ').map(function(roomsHotel) {
    return {number: roomsHotel};
  });
  $scope.adultsHotel = ('1 2 3 4 5 6 7 8 9 10 11 12 13 14 15').split(' ').map(function(adultsHotel) {
    return {number: adultsHotel};
  });

  $scope.submitHotelsCtrl = function(response){  
    var rooms = [];
    var totalAdults = parseInt(this.adultsHotels);
    var roomsToFill = parseInt(this.rooms);
     var roomsSelected = parseInt(this.rooms);

    var maxPeopleInRoom = Math.ceil(totalAdults/roomsToFill);      
    for(var j=0; j < roomsSelected; j++){

      if(roomsToFill > 1){
        if(totalAdults >= maxPeopleInRoom){
        var peopleToOccupyInRoom = Math.ceil(totalAdults/roomsToFill);
        totalAdults-=peopleToOccupyInRoom;
        rooms.push({'adults': peopleToOccupyInRoom});
        roomsToFill--;
        }else{
          rooms.push({'adults': totalAdults});    
        }
      }else{
        rooms.push({'adults': totalAdults});  
      }
    }

  var data = {'rooms': rooms
},myObjJSON = JSON.stringify(data);
console.log(data);
console.log(rooms);
}
});

While this code may have room for improvement, it should address your current needs. Please let me know if the issue persists.

Here is the updated plunker link

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

Steps for creating a JavaScript session expiry notification:

Ensuring user session continuity is essential, especially before it expires. In a recent quest on Stack Overflow, I inquired about detecting a dead session and alerting the user. A solution involving AJAX/JSON was proposed, but it inadvertently kept the s ...

Passing values between a JavaScript function and a PHP script - Here's how!

I am looking to display the output of a PHP script in a div tag without having to refresh the page. I have a collection of .c files that users can compile on the server, and I want to list them in a dropdown like this: <option value="" selected="select ...

The quickest regular expression match possible if it is already a subsection of another match

Is there a simple way to find the shortest match in a long text where strings are repeated? I'm having trouble because matches within already matched text aren't being found. Here's an example of the issue: Using code: "ababc".match(/a.+c ...

Failure to give an error message occurred during a POST request on Parse.com and ExpressJS platform

I'm facing an issue where a POST request I send fails with error code 500 and there is nothing showing up in my server side error log. It seems like the cloud method may be missing. What's interesting is that the same POST request works fine wit ...

Using Conditional References within a JSON Schema

My goal is to create a single-file JSON schema definition with multiple sub-schemas that can be combined based on the payload. The schema below validates that my schema is functioning correctly with a sample JSON response that intentionally has an error in ...

Giving identification to a pair of elements located within the same column

Struggling with assigning IDs to two elements in a single column - a dropdown and a text element. Managed it in the first scenario, but encountering issues in the second one. Seeking assistance on this matter. Scenario 1: <td> <sele ...

Utilizing JSON object retrieval within a Node.js server

Recently, I started working with Node server. I have written a program that fetches data from a database like this: connection.query("SELECT * from login where username='" + uname + "' and password='" + pwd + "' ", [uname, pwd], functi ...

The use of Next.js v12 middleware is incompatible with both node-fetch and axios

I am facing an issue while developing a middleware that fetches user data from an external endpoint using Axios. Surprisingly, Axios is not functioning properly within the middleware. Below is the error message I encountered when using node-fetch: Module b ...

Tips for delivering a variable to a React Native Stylesheet

Is there a way to pass a variable to the "shadowColor" property in my stylesheet from an array declared in the code above? I keep encountering a "Can't find name" error. Attempting to use a template literal has not resolved the issue. Any assistance w ...

What is the best way to simultaneously update the model and view values in an Angular directive?

My apologies if directives are not my strong suit! Within this simple attribute-only directive, the primary goal is to automatically convert a string in a field to an HH:mm format upon blurring the field. The directive code is as follows: (function () { ...

Utilizing Node.js to transmit information to an ejs file and retrieving data using Angular.js

I'm facing an issue here. I am struggling to figure out how to pass data from a node.js file to an ejs file and then retrieve that data using Angular.js Node.js segment app.get('/', function(req, res) { connection.query('SELECT * F ...

The data does not seem to be getting sent by the res.send() method in

I'm having trouble with the GET request not returning the data I expect. Here is my GET request code: router.get('/', (req, res) => { res.set('Content-Type', 'text/html') res.status(200).send(Buffer.from('<p& ...

What is the best way to utilize jquery's $.ajax function in conjunction with json and php to upload a file?

Can someone assist me with uploading a file using jQuery's $.ajax function? I am not getting any output and I'm unsure if my script is correct. Here is the code: $.ajax({ url:'newsup.php', data: "", type: 'POST', cont ...

Ways of assigning specific colors to individual categories?

We currently have a code that allows us to draw circles on the map location with the name of each category. However, both the circles and text are in the same color. Is there a way we can assign different colors based on the category? For example, Category ...

"Learn the best way to send a list to a function and add a new item

I'm new to Java and currently trying to develop a method for a list that adds elements to the list and returns it. However, I keep encountering this error: Exception in thread "main" java.lang.Error: Unresolved compilation problem: language ca ...

What causes array_diff to behave in a unique manner when comparing arrays obtained from an input form?

I have created an input form with three text areas: <form method="POST" action="unique_value_processor.php"> <textarea cols="50" rows="8" name="usedurls"></textarea> <textarea cols="50" rows="8" name="freshurls"></textarea> & ...

Efficiently Filtering User Input and Other Things

Imagine I have a setup for organizing a television guide like this: <div class="day"> <p>A Date</p> <div class="time"> <p>A Time</p> <div class="show"> <p>A Show</p> ...

What is the proper way to implement the post method in Android's MVC pattern?

As someone who is new to integrating the MVC pattern with JSON post method on Android, I am looking for guidance on how to successfully post the provided data using JSON to the URL . Can someone assist me with implementing the MVC pattern in Android? ME ...

Updating the web browser does not display the changes made on the page

Currently diving into the world of Angular and I've successfully cloned the repository. After installing the dependencies using npm, I have the web server up and running smoothly. Accessing the page on localhost:4000 works like a charm. Interestingly ...

Utilizing Packery.js in AngularJS

Having some trouble trying to integrate Packery.js with my angularjs app. It seems like they are not working well together. I tried setting isInitLayout to false, but no luck. This is the (bootstrap 3) HTML code I am using: <div class="row" class="js ...