Simply input the data into the fields of the weekly tds

I am facing an issue with my code where, upon clicking the "apply to all" button, it automatically populates the columns for Monday through Friday only. However, I need Saturday and Sunday to remain empty without any data.

$('#elemento').click(function() {
  var checkedValues = Array(8).fill(false);
  var textValues = Array(7).fill('');
  var checkedStep = 0;
  var textStep = 0;
  var data_idparcela = [];
    $("[data-day]").each(function() {data_idparcela.push(this.value)});

    for(var i = 0; i < data_idparcela.length; i++){
       
      var id_data = new Date(data_idparcela[i]);
      var id_data = id_data.getDay();
       
      
      $('tr').find('input[type="checkbox"]').each(function(index, value){
        if(index < 8){
          checkedValues[index] = $(this).prop("checked");
        }else{
          if(checkedStep == 8){
            checkedStep = 0;
          }



          if (id_data >= 1 && id_data <= 5) {
            $(this).prop('checked', checkedValues[checkedStep++]);
          }
          else {
            checkedStep++;
          }

        }
      });
      $('tr').find('input[type="text"]').each(function(index, value){
        if(index < 7){
          textValues[index] = $(this).val();
        }else{
          if(textStep == 7){
            textStep = 0;
          }

          if (id_data >= 1 && id_data <= 5) {
            $(this).val(textValues[textStep++]);
          }
          else {
            textStep++;
          }
        }
      });
     
     }
  
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<button id="elemento">Apply to All </button>

<table>
  <tr>
    <th>Thursday</th>
    <th>Friday</th>
    <th>Saturday</th>
    <th>Sunday</th>
    <th>Monday</th>
    <th>Tuesday</th>
    <th>Wednesday</th>
  </tr>
  
  <tr>
    <td>
      <div id='dia4'>
        <input type="checkbox" data-day='' value="2022-11-01">2022-11-01
        
        <div>
          <input type="checkbox" name="vehicle" value="Bike">Breakfast
          <input type="text" size="10">
        </div>
        
        <div>
          <input type="checkbox">Lunch
          <input type="text" size="10">
        </div>
        
        <div>
          <input type="checkbox">Diet Lunch
          <input type="text" size="10">
        </div>
        
        <div>
          <input type="checkbox">Snack
          <input type="text" size="10">
        </div>
        
        <div>
          <input type="checkbox">Dinner
          <input type="text" size="10">
        </div>
        
        <div>
          <input type="checkbox">Diet Dinner
          <input type="text" size="10">
        </div>
        
        <div>
          <input type="checkbox">Supper
          <input type="text" size="10">
        </div>
      </div>
    </td>>
    ... (continued)
  </tr>
</table>

The issue arises when the "apply to all" button is clicked as it fills in all days including Saturday and Sunday.

To tackle this problem, I retrieve the date from each td using getDay() function to convert the days into numbers. Then, a condition should only populate the columns for days between Monday and Friday (numbered 1-5), while skipping Saturday and Sunday (numbered 0 and 6).

Answer №1

Perhaps this solution will work for your needs?

Please take note: I have removed the duplicate ids from your <div> elements and replaced them with class attributes.

I also went ahead and utilized a template string to streamline your HTML generation process, reducing repetition significantly.

Take a look at this condensed HTML snippet that can be used to construct the remainder of the table (the "second part" has been adjusted to work with both versions of the HTML):

// first part, generates the table from a template
// ===============================================
$("table:first tbody").html(Array(7).fill(0).map((_,i)=>{
  let d=String(1+i).padStart(2,'0');
  return `<td>
      <div class="dia">
        <input type="checkbox" data-day='' value="2022-11-${d}">2022-11-${d}
        <div><input type="checkbox" name="vehicle" value="Bike">Peq.Almoço<input type="text" size="10"></div>
        <div><input type="checkbox">Almoço<input type="text" size="10"></div>
        <div><input type="checkbox">Almoço (Dieta)<input type="text" size="10"></div>
        <div><input type="checkbox">Lanche<input type="text" size="10"></div>
        <div><input type="checkbox">Jantar<input type="text" size="10"></div>
        <div><input type="checkbox">Jantar (Dieta)<input type="text" size="10"></div>
        <div><input type="checkbox">Ceia<input type="text" size="10"></div>
      </div>
    </td>`}).join("\n"));

// second part, works with both, the original and the changed HTML
// ===============================================================
const tbd=$("table:first tbody"),
  inps = $("td:first input",tbd).get(),
  wd=$("table:first th").get().map(t=>t.textContent);


$('#elemento').click(function() {
  $("td",tbd).each(function(j) {
    if(!["Saturday","Sunday"].includes(wd[j]))
      $("input", this).each((i, inp) => $(inp).val(inps[i].value).prop("checked", inps[i].checked));
  })
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="elemento">Apply to All </button>
<table>
  <thead>
    <tr><th>Tuesday</th><th>Wednesday</th><th>Thursday</th>
        <th>Friday</th><th>Saturday</th><th>Sunday</th><th>Monday</th></tr>
  </thead>
  <tbody></tbody>
</table>

Second Update

Below is the revised version with the detailed "original" HTML content. It was observed that there were inaccuracies in the weekdays within the column headers (<th>), which have now been corrected. Additionally, I have adjusted the column selection method to verify the date value of the [data-day]-checkbox in each column to determine whether it pertains to a working day (excluding weekends):

if(![0,6].includes(new Date($("[data-day]",this).val()).getDay())) { do stuff ...}

Here is the complete functioning code snippet:

// second part, works with both, the original and the changed HTML
// ===============================================================
const tbd=$("table:first tbody"),
  inps = $("td:first input",tbd).get();

$('#elemento').click(function() {
  $("td",tbd).each(function(j) {
    if(![0,6].includes(new Date($("[data-day]",this).val()).getDay()))
      $("input", this).each((i, inp) => $(inp).val(inps[i].value).prop("checked", inps[i].checked));
  })
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="elemento">Apply to All </button>
<table>
  <tr>
<th>Tuesday</th>
<th>Wednesday</th>
<th>Thursday</th>
<th>Friday</th>
<th>Saturday</th>
<th>Sunday</th>
<th>Monday</th>
  </tr>
  
  <tr>
... (HTML structure continues here)
  </tr>
</table>

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

JavaScript is not designed to run a second time

Currently, I have a script set up using $(document).ready(). It works perfectly upon initial loading. However, I also need this script to execute whenever the user changes an HTML select control. Ideally, upon page load, I want the filter and sort functio ...

What is the syntax for accessing an element within an array in a function?

This code snippet retrieves an array of users stored in a Firestore database. Each document in the collection corresponds to a user and has a unique ID. const [user] = useAuthState(auth); const [userData, setUserData] = useState([]); const usersColl ...

Mastering the map() function in Vue.js 2

As I start learning vue.js, I am facing some challenges. I need to implement a dictionary analog in JavaScript, known as a map. However, I'm unsure of where to define it. The map should be utilized in both the checkDevices() method and within the HTML ...

Encountered an issue while trying to implement CORS using yarn

Currently experiencing the following issue: Error message: An unexpected error occurred "/home/vagrant/.cache/yarn/v1/npm-cors-2.8.4-2bd381f2eb201020105cd50ea59da63090694686/.yarn-metadata.json: Unexpected end of JSON input". Some important points to c ...

intl-tel-input's getExtension function is returning a value of 'null'

I've been attempting to retrieve the extension of the mobile number that has been input. All other variables are functioning correctly, but the extension variable is returning a null value. It appears that it is sending a null value to the POST method ...

"Troubleshooting 3D Models not appearing correctly in Mapbox when using Three.js

My issue lies in the inability to load any .gltf file, only a standard one. For further details, please continue reading. The map on my application showcases a 3D model indicated by the red arrow: https://i.sstatic.net/3Ce09.png The model is a GLTF file ...

In order for the Facebook share button to appear, a page reload is required when using Angular

I've been working on integrating Facebook's share plugin, but I've encountered an issue where the share button only shows up after reloading the page. If I navigate to the page through a link or URL, the button doesn't appear until afte ...

Adjust the margin of a child div based on the parent's width, with the use of JavaScript

Currently, I am developing a website at and I am interested in replicating the layout of another site. The site I would like to emulate is , which features multiple sections with child divs that have margins around them. In order to achieve this effect o ...

What is the best way to check for changes in value using the onchange

The function is encountering an error and failing to execute. Despite my attempts to check for the onchange property in order to prevent errors, I keep receiving an error message stating "Cannot read property 'onchange' of undefined." Below i ...

Learn how to use canvas and JavaScript to draw lines that display x and y coordinates on top of the mouse pointer at the same time

Implement a functionality in which lines are drawn while the mouse button is held down and simultaneously display x & y coordinates on top of the mouse pointer during mouse movement using canvas and JavaScript. The issue arises when attempting to draw lin ...

Running cy.task after all test suites can be done by adding the task in a

I need some guidance on running cy.task after executing all test suites. I have a file generated at the start of the tests that I would like to remove once they are completed. Regardless of whether any tests passed or failed, I want to trigger cy.task im ...

Do you think it's wise to utilize React.Context for injecting UI components?

I have a plan to create my own specialized react component library. These components will mainly focus on implementing specific logic rather than being full-fledged UI components. One key requirement is that users should have the flexibility to define a se ...

Utilizing JQuery UI autocomplete for dynamically loaded textbox using AJAX

<div id='toolbox'> <div class='placeholder'></div> </div> In my project, I am using a click event to dynamically load a text box into the placeholder. $('#toolbox .placeholder').load('http:// ...

How can I implement jQuery autocomplete with customized settings?

In my Drupal project, I am looking to implement jQuery's auto complete feature to search for nodes based on their titles. I am having trouble finding examples that align with my specific requirements: The URL structure should be: /api/node/title/{wh ...

Tips for switching a group of buttons within a userscript by clicking a single button?

Apologies if my wording is not clear, allow me to clarify. I am in the process of developing a userscript that will display a set of buttons below a main button when clicked. These additional buttons will serve different functions and should disappear whe ...

What is the best way to manipulate a shape in Snap.svg while ensuring the transformation does not affect its mask?

My current challenge involves transforming a rectangle with position, scale, and angle adjustments while having it masked. To illustrate my issue, I have created a fiddle file which can be accessed via this link: http://jsfiddle.net/MichaelSel/vgw3qxpg/2/ ...

Displaying a webpage within a div section of another webpage by referencing it from a separate webpage

If I have three html pages named index.html, page1.html, and page2.html. Imagine that I am currently on page2.html and there is a list of items, each linking to different pages. Let's say one item links to page1.html. Is it feasible to load page1.ht ...

Swapping values between HTML tables and arrays with the power of JavaScript

I have a unique table structure that I need help with: https://i.sstatic.net/fr7oJ.png My current table has 2 rows and multiple columns, but I want to change it to have 2 columns and multiple rows like this: https://i.sstatic.net/uhkp9.png To create th ...

What is the procedure for selecting an element based on its child containing specifically filtered text?

Imagine a webpage with the following elements: <div data-search="type1"> any HTML <!-- .click is a child of any level --> <span class="click" data-source="page1.html">blue</span> <!-- let's call it "click1 ...

When an ajax request fails with error 500, the Jquery script will come to a halt

I currently have a script that sends ajax requests at regular intervals and it is intended to keep working indefinitely. <script type="text/javascript"> var delay = 750; window.setInterval(endlessJob, delay); function endlessJob() { ...