Populate table cells dynamically using an array of elements

I am trying to dynamically change the background color of table cells based on their values. Here is an example of the code I have written:

applySchedules = function(schedules){
    $.map(schedules, function(value, index){
        $('#'+value.start).css('background', 'green');
    });
}

var temp = [{start:9, end:10}, {start:13, end:14}]
applySchedules(temp);
tr {
   border-width:2px; 
   outline:solid;
}
td {
   border-width:2px; 
   width:60px; 
   outline:solid;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> 
<table>
    <tr>
        <td id="8">8AM</td>
        <td id="9">9AM</td>
        <td id="10">10AM</td>
        <td id="11">11AM</td>
        <td id="12">12PM</td>
        <td id="13">1PM</td>
        <td id="14">2PM</td>
        <td id="15">3PM</td>
        <td id="16">4PM</td>
        <td id="17">5PM</td>
        <td id="18">6PM</td>
        <td id="19">7PM</td>
        <td id="20">8PM</td>
    </tr>
</table>

Essentially, I receive a JSON array containing time slots that are reserved for a specific day. The challenge arises when a slot spans more or less than one hour because time slots are in increments of 30 minutes.

For example:

{start:10,end:11.30},{start:12,end:12.30},{start:14.30,end:15}

I am seeking advice on how to handle these types of scenarios.

Sample Output : https://i.sstatic.net/lku5Z.png

Answer №1

Here's some advice to consider:

  1. Increasing the number of spans can help accommodate your 30-minute item.
  2. Avoid using just numbered IDs as it may not be the most effective approach.

$(function(){
   var applySchedules = function(schedules){
   $.map(schedules, function( value,index){
         
         var startHour = value.start.split(":")[0];
         var endHour = value.end.split(":")[0];
         var halfStart = value.start.split(":")[1];
         var halfEnd = value.end.split(":")[1];
         
         var startContainer = $('#time'+ padLeft( startHour, 2));
         var endContainer = $('#time'+ padLeft( endHour, 2));
   
             if( parseInt( halfStart )){
               startContainer.append( $("<div />").addClass("start") );
             }
             if( parseInt( halfEnd )){
               endContainer.append( $("<div />").addClass("end") );
             }
         
          if( ( parseInt(endHour) - parseInt(startHour) ) > 0){
            for( var i = 1; i < parseInt(endHour) - parseInt(startHour); i++ ){
              
               $('#time'+ padLeft( (parseInt(startHour) + i)+"", 2)).append( $("<div />").addClass("full") );
            }
          }
         
   });
   }
   function padLeft(str,size,padwith) {
if(size <= str.length) {
return str;
} else {
return Array(size-str.length+1).join(padwith||'0')+str
}
   }
  
   
   var initTime = function(){
     for( var i =0; i< 24; i++ ){
       var $item;
       if( i < 12  ){
         $item = $("<td/>").text( padLeft(i+"",2)+":00 AM" );
       }else if( i == 12 ){
         $item = $("<td/>").text( padLeft( (i)+"",2)+":00 PM" );
       } else {
         $item = $("<td/>").text( padLeft( (i-12)+"",2)+":00 PM" );
       }
       $item.attr("id", "time" + padLeft(i+"",2));
       $("#timeContainer").append($item);
     }   
   }
   
   var temp=[{start:"9:00",end:"9:30"}, {start:"13:00",end:"13:30"}, { start:"14:00", end:"14:30"}, {start:"15:30", end:"18:30"}]
   initTime();
  applySchedules(temp);
  
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<style>
tr{border-width:2px; outline:solid;}
td{border-width:2px; width:60px; outline:solid; position:relative;}
  div.start {
      width: 50%;
    background: green;
    position: absolute;
    height: 100%;
    top: 0;
    right: 0;
    z-index:-1;
}
div.end {
    width: 50%;
    background: green;
    position: absolute;
    height: 100%;
    top: 0;
    left: 0;
  z-index:-1;
}
  div.full{
    width: 100%;
    background: green;
    position: absolute;
    height: 100%;
    top: 0;
    z-index:-1;
  }
  
</style>
<body>
<table>
<tr id="timeContainer">
</tr>
</table>

</body>


UPDATED ANSWER Some initial ideas on coding strategies

Answer №2

If you're determined to stick with your current setup, I'd recommend using CSS gradients:

...
$('#'+value.start).css('background','repeating-linear-gradient(to right, #00FF33, #00FF33 23px, #FFFFFF 23px, #FFFFFF 46px)');
...

The width of 46px in the <td> from the fiddle may need to be dynamically generated. The second two values are half of the whole <td> width, creating a gradient that covers only half. If you want smaller sections, you can get more complex with the math, but I recommend checking out https://css-tricks.com/stripes-css/ for more details on this technique.

Here's the fiddle:

http://jsfiddle.net/85mJN/190/

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

Invalid Jquery syntax: Anticipated an assignment or function call but encountered an expression instead

Here's a simple code snippet: _create: function () { var self = this; $("#Grid").on("click", ".Row", function () { $(self).hasClass('Expanded') && $('html, body').animate({ ...

Instructions on transforming a XAML grid in WPF into a JSON array

Currently, I am utilizing a XAML WPF grid in my project and I am looking to transform the structure of the grid into JSON format. Do you have any suggestions or ideas on how this can be achieved? For reference, here is an example: <GridBinding> ...

Revitalize website when submitting in React.js

I need assistance with reloading my React.js page after clicking the submit button. The purpose of this is to update the displayed data by fetching new entries from the database. import React, {useEffect, useState} from 'react'; import axios from ...

How can I combine multiple textures from mtlLoader and objLoader in three.js?

I have the files .mtl, .obj, and several .jpg textures. I have been attempting to use different textures in the export loader OBJ, and while I can see my object on the scene, it appears as a black color. Can anyone spot what might be incorrect or missing ...

Executing functions in a loop using Angular

Within my component, there is a foreach loop triggered when a client is selected. Inside this loop, I need to execute a function within the same component. The issue arises with calling the function using `this.functionName()` because 'this' no ...

Modify the textfield label color using Material-UI

Hey there! I'm running into a little issue when trying to change the color of the text label in a MUI text field. I've successfully customized the border colors and hover states, including the label, but for some reason, I can't seem to get ...

Is there a way to monitor real-time updates without relying on setInterval or timeout functions?

Currently in the process of building a social network, I am working on fetching live notifications. The current approach involves sending an AJAX request every few seconds using setInterval. The code snippet for this operation is as follows: setInterval ( ...

Conceal one object when the other is revealed?

Is there a way to hide the element with the class .close-button while showing another element with the ID #loading-animation? Can jQuery conditionals help achieve this? For example: if ($('#loading-animation').is(':visible')) { $ ...

Rows in the table mysteriously vanish when you switch to the following page

I am a beginner with React and I am currently using an addrow method to populate a table that I created using {this.state.rows.map}. The table successfully displays the values from the input fields. However, when I navigate away using the continue button a ...

Issue in insert.php file: stdClass::$variable property is undefined when using Ionic, Angular, and PHP together

There are three files. Once the submit button is clicked on the Ionic page, all inputs will be sent to the controller, which will then parse them to insert.php. The form input data is saved successfully when only using HTML (without Ionic content), however ...

Guide to activating the timer specifically on select pages with jQuery Mobile

I've developed a quiz application using jQuery Mobile and I am working on implementing a timer feature. The timer should run from 0 seconds up to 1 hour but only when the user is viewing specific pages, specifically the question pages. The timer is di ...

Jquery attribute not functioning correctly when setting the 'required' property for checkboxes

One of the challenges I am facing is trying to toggle a text box on a checkbox's click event. While I have achieved success in this aspect, my issue lies in changing the checkbox's required attribute as well. Below is the code that successfully ...

Tips for organizing data when parsing JSON in Javascript

I am facing a challenge with maintaining the order of JSON data that I am parsing using Javascript and displaying in an HTML SELECT element. The incoming data is already sorted, but I am encountering issues sustaining this order after decoding the JSON str ...

Vertical words standing alongside an upright line

My goal is to rotate the text without any issues, but I'm having trouble with the line underneath it. The line should adjust its length based on the length of the text. In other words, as the text changes in length, the line should shrink or expand ac ...

Guidelines for executing a PHP script upon a button click

I am new to learning PHP. I have a jQuery code that I need to implement in PHP. The active class simply changes display:none to display:block. You can find the code here. $(document).ready(function(){ $(".cecutient-btn").click(function(){ event. ...

This is the command that includes the line "test": "tsc && concurrently "karma start karma.conf.js""

When running npm run test with the line "test": "tsc && concurrently \"karma start karma.conf.js\"" in my package.json, I encounter the error message 'Error: no test specified'. Can someone guide me on how to resolve this issue? ...

Attempting to implement bootstrap pagination using PHP mysqli

Hi there, I'm currently working on implementing a pagination feature using Bootstrap. My goal is to display all results from mySQL data while limiting the data to 10 entries per page. I would appreciate any assistance with this. Here's the code I ...

Creating an HTML table from an array of objects: A step-by-step guide

Is there a way to create an HTML table from an array of objects? I attempted the following code but encountered an object error: data: [{ "slot": "10:00-11:00", "isBooked": false }, { "slot": "11:00-12:00", "isBooked": false }, { "slot": "12:00-13:00", " ...

Navigating the coordinates for iframe integration in angular js

Hey there! I've been working with Angular and attempting to integrate an iframe. I have tried various methods to insert the longitude and latitude values from the database, but every time I try to input something like this, I encounter an error. Her ...

Obtaining the attribute value of a disabled element in an Angular JS application

Currently, I am struggling to retrieve the attribute value of a disabled element during runtime and then assert its value. The code I'm using is not providing the desired result: softAssert.assertFalse(shrSub.nextButton().waitForPresent().getAttribu ...