Viewing the JSON Data

Support:

$scope.createTimeSlots = function(interval, field) {
    var startingTime = moment().hours(8).minutes(0);
    field.timeslots = [];
    for (var i = 0; i < interval; i++) {
        $scope.intervals = 60;
        field.timeslots.push(startingTime.add($scope.intervals, 'minute').format("h:mm"));
    }
}
$scope.SavePreferences = function(companyName, form_settings) {
        var _settings = {
            'company': companyName
        };
        console.log(_settings);
        debugger;
        var WorkingDays = [];
        for (var i = 0; i < $scope.fields.length; i++) {
            var item = $scope.fields[i];
            var time = $scope.fields.timeslots;
            if (item.checked) {
                WorkDays.push(item.name, time.timeslot);
            }
            console.log(time);
        }

link

I have arranged each day in a row with dropdowns and textboxes. My aim is to showcase the selected checkboxes values along with corresponding data in textbox and drop-down, displayed in JSON format

{'day':Monday,'duration':3,'drop-down':10.00}
. However, there seems to be an issue displaying the selected days alongside their duration and timeslot. How can I correct this JSON display?

Answer №1

Take a look at this code snippet.

Here are the modifications:

  • Create a function setSelectedSlot that saves the selected slot for each field object.
  • Attach the previous function to a change event of the select element.
  • Also, store the duration (interval) in the field object when setTimeSlots is invoked.

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

app.controller('MainCtrl', function($scope) {
  $scope.fields = [{ id: 1, name: 'Sunday', timeslots: [] },
      { id: 2, name: 'Monday' },
      { id: 3, name: 'Tuesday' },
      { id: 4, name: 'Wednesday' },
      { id: 5, name: 'Thursday' },
      { id: 5, name: 'Friday' }];

      $scope.setTimeSlots = function (interval, field) {
         var startingTime = moment().hours(8).minutes(0);
         field.timeslots = [];
         // This was added
         field.duration = interval;
         // end of changes
         for(var i=0; i < interval; i++){
         $scope.intervals=60;
         field.timeslots.push(startingTime.add($scope.intervals,'minute').format("h:mm"));
    }
   }
   // This function is new
   $scope.setSelectedSlot = function(field) {
     field.selectedSlot = this.time;
   }
   // end of changes
   $scope.Savesettings=function(){
      $scope.workDays=[];
      for(var i=0; i<$scope.fields.length;i++){
         var item = $scope.fields[i];
         if(item.checked){
            // The following line changed
            $scope.workDays.push({"day": item.name, "drop-down": item.selectedSlot, "duration": item.duration});
            // end of changes
         }
      }
     console.log($scope.workDays);
   }
  
});
<!DOCTYPE html>
<html ng-app="plunker">

<head>
  <meta charset="utf-8" />
  <title>AngularJS Plunker</title>
  <script>
    document.write('<base href="' + document.location + '" />');
  </script>
  <link rel="stylesheet" href="style.css" />
  <script data-require="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="97f6f9f0e2fbf6e5b9fde4d7a6b9a2b9ef">[email protected]</a>" src="https://code.angularjs.org/1.5.8/angular.js" data-semver="1.5.8"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.js"></script>
  <script src="app.js"></script>
</head>
Result => {{workDays}}
<body ng-controller="MainCtrl">

  <table>
    <tr ng-repeat="field in fields" name="slotSelection">
    <td align="center">
      <input type="checkbox" ng-model="field.checked">{{field.name}} 
    </td>
    <td>
      <!-- Bind a new function to the `change` event -->
      <select ng-model="time" ng-options="time for time in field.timeslots" ng-change="setSelectedSlot(field)">
      <!-- end of changes -->
        <option value="">select</option>
      </select>
    </td>
    <td>
      <input type="text" ng-model="interval" ng-blur="setTimeSlots(interval, field)">
    </td>
  </tr>
  </table>
  <button ng-click="Savesettings()">Submit</button>
</body>

</html>

Answer №2

Issues Identified:

1: WorkDays is not defined. 2: field does not have time and interval properties associated with it

Suggested Changes:

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

app.controller('MainCtrl', function($scope) {
  $scope.fields = [{ id: 1, name: 'Sunday', timeslots: [] },
      { id: 2, name: 'Monday' },
      { id: 3, name: 'Tuesday' },
      { id: 4, name: 'Wednesday' },
      { id: 5, name: 'Thursday' },
      { id: 5, name: 'Friday' }];

      $scope.setTimeSlots = function (interval, field) {
         var startingTime = moment().hours(8).minutes(0);
         field.timeslots = [];
         for(var i=0; i < interval; i++){
         $scope.intervals=60;
            field.timeslots.push(startingTime.add($scope.intervals,'minute').format("h:mm"));
    }
   }
   
   $scope.Savesettings=function(){
      $scope.workDays=[];
      for(var i=0; i<$scope.fields.length;i++){
         var item = $scope.fields[i];
         if(item.checked){
            
			var obj = {"day":item.name,"duration":item.interval,"drop-down": item.time,}
           
            $scope.workDays.push(obj);
         }
      }
   }
  
});
<!DOCTYPE html>
<html ng-app="plunker">

<head>
  <meta charset="utf-8" />
  <title>AngularJS Plunker</title>
  <script>
    document.write('<base href="' + document.location + '" />');
  </script>
  <link rel="stylesheet" href="style.css" />
  <script data-require="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1c7d727b69707d6e32766f5c2d32293264">[email protected]</a>" src="https://code.angularjs.org/1.5.8/angular.js" data-semver="1.5.8"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.js"></script>
  <script src="app.js"></script>
</head>

<body ng-controller="MainCtrl">
  <table>
    <tr ng-repeat="field in fields" name="slotSelection">
    <td align="center">
      <input type="checkbox" ng-model="field.checked">{{field.name}} 
    </td>
    <td>
      <select ng-model="field.time" ng-options="time for time in field.timeslots">
        <option value="">select</option>
      </select>
    </td>
    <td>
      <input type="text" ng-model="field.interval" ng-blur="setTimeSlots(field.interval, field)">
    </td>
  </tr>
  </table>
  <button ng-click="Savesettings()">Submit</button>
  {{workDays}}
</body>
</html>

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

How can we efficiently iterate through an array in Node.js while making asynchronous calls?

I need to iterate through an array, pushing a new Thing to a list in the process. The Thing itself performs asynchronous calls. However, I am facing an issue where my for loop is synchronous but the new Things are asynchronous, causing the callback to be c ...

Creating interactive PDF files using ReactJS

Is there a way to create a PDF using React that supports styling and allows the content to be hidden on the page? I need to have a link in my app that, when clicked, generates a PDF and opens it in a new tab. I've tried out various packages but none s ...

Fill in input field based on choice from the drop-down menu - JavaScript

I am facing an issue where I cannot add text inside the text box based on the dropdown selection. For example, if I select option2 from the dropdown, the textbox should be populated with option2. (function() { 'use strict'; setInterva ...

What is the best way to pass a custom HTTP header to a Node.js server?

One of my current challenges involves utilizing jQuery to include a custom header in each AJAX request. $.ajaxSetup({ beforeSend: function (xhr) { xhr.setRequestHeader ("Authorization", "Basic " + btoa(user + ":" + sessionID)); }, }); My ...

What is the best way to extract information from a JSON field in PostgreSQL?

I'm having trouble parsing the 'attributes' JSON field in a unique way: select attributes -> 'foo' from schema.table This JSON field is structured in a key-date-value format that's new to me. In Postgres, how do I extrac ...

Guess the Number Game with while Loop

I have a project where I need to limit guesses to 10, display the guessed number, and keep those results on the screen after each game without replacing the previous guesses. Each set of guesses should be numbered to show how many guesses have been made us ...

Reading an irregular JSON file with AngularJS if statement

I received a json data with the following structure: [ { "level" : "1", "name" : "TIER 1 - CORE FOUNDATIONS", "required" : "13", "completed" : "9", "planned" : "0", "subcategories" : [ { "level" : "2", ...

Deactivate a particular function key with the help of jQuery

Is there a way to disable the F8 key on a web page using jquery, plugins, or just javascript? Thank you in advance! :) blasteralfred ...

Having trouble with threejs: Trying to map converted JSON animations to sliders but facing some issues

After converting a skinned.dae mesh to JSON using this loader, I am working on loading it up in a scene and mapping its animations to sliders for model posing purposes. Here is the relevant code snippet: var loader = new THREE.JSONLoader(); var animation; ...

"Troubleshooting issue: Unable to retrieve grid data from Google Sheets API v4 when integrated

I've implemented a function within a React component that retrieves JSON data from an API request and logs it: async function getAllSheets() { let response; try { response = await window.gapi.client.sheets.spreadsheets.values.batchGet( ...

Creating a cascading layout with React Material-UI GridList

Can the React Material-UI library's GridList component be used in a layout similar to Pinterest's cascading style? I have utilized Material-UI Card components as children for the GridList: const cards = props.items.map((item) => <Card ...

Issue with applying value changes in Timeout on Angular Material components

I'm currently experimenting with Angular, and I seem to be struggling with displaying a fake progress bar using the "angular/material/progress-bar" component. (https://material.angular.io/components/progress-bar/) In my "app.component.html", I have m ...

Checking the Ajax request with an if statement

$("#Submit").click(function(event){ event.preventDefault(); var th = '<tr><th>' + "Business" +'</th><th>' + "Address"+ '</th><th>'+ "Rating" + '</th><th>' + "Da ...

SyntaxError: Unexpected '<' symbol found in JavaScript file while attempting to import it into an HTML document

This issue is really frustrating me In my public directory, there is an index.html file Previously, I had a newRelic script embedded within the HTML in script tags which was functioning properly Recently, I moved the script to a separate JavaScript file ...

Retrieve JSON response from server using Swift to decode

I am currently encountering an issue with parsing the data response from the server and converting it to JSON format using Swift. Previously, the response was returning as JSON but now, with additional attributes added, it returns a string. When trying to ...

What is the best way to set a specific image as the initial image when loading 'SpriteSpin'?

I'm currently working on creating a 360-degree view using the SpriteSpin API. Everything is functioning as expected, but I have an additional request. I need to specify a specific image to be the initial landing image when the page loads. The landing ...

When a previous form field is filled, validate the next 3 form fields on keyup using jQuery

Upon form submission, if the formfield propBacklink has a value, the validation of fields X, Y, and Z must occur. These fields are always validated, regardless of their values, as they are readonly. An Ajax call will determine whether the validation is tru ...

Match one instance of a character in a regular expression pattern while simultaneously matching two occurrences of a different character

I am attempting to create a function that can match one occurrence of a certain character and two occurrences of another character simultaneously. For instance, in the string "_Hell_o", I want to match the first underscore (_) and in the string "++Hello", ...

How to extract JSON data without HTML tags in Android Studio

i'm done with my android studio project. i have successfully stored data from wp-json. however, there seems to be an issue where I am getting the following: <p>আল্লামা আহমদ শফীর ইন্তেকালের পর ...

The <h> tag gains height on its own accord

Here is my original code: <h4 class="orange2" ><a href="<?php echo base_url();?>v/<?php echo $this->uri->segment(3);?>/<?php echo $v['uniq'];?>"><?php echo trim(strip_tags($v['video_name']));?> ...