Home > Blockchain >  jquery datepicker insert dayid to all days within <td> attribute
jquery datepicker insert dayid to all days within <td> attribute

Time:09-21

datepicker

I need to add dayid to all <td>, for example:

<td  data-year="2022" data-month="8" data-event="click" data-handler="selectDay">
 <a  href="#">22</a>
</td>

would be like

<td  data-year="2022" data-month="8" dayid="22" data-event="click" data-handler="selectDay">
  <a  href="#">22</a>
</td>

<td  data-year="2022" data-month="8" dayid="23" data-event="click" data-handler="selectDay">
  <a  href="#">23</a>
</td> ... and so on

is this possible in jquery? I started writing this

$('td')
 .filter('[data-year="2022"]')
 .filter('[data-month="08"]')
 .find('a') // find all Anchors in this filtered result
 .attrib('dayid', '');

but don't think it can work as I don't want to hardcode the year & month, and can't get the value of each to set the attribute

CodePudding user response:

You can start from the a and assign it's text() to the containing td

$('td[data-year] a').each(function(i, o) {
  $(o).closest('td').attr('dayid', $(o).text())
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <tr>
    <td  data-year="2022" data-month="8" data-event="click" data-handler="selectDay">
      <a  href="#">22</a>
    </td>
  </tr>
  <tr>
    <td  data-year="2022" data-month="8" data-event="click" data-handler="selectDay">
      <a  href="#">23</a>
    </td>
  </tr>
</table>

CodePudding user response:

This is not exactly what you asked but here is one way to get all the days of the current calendar using the data-date attributes the calendar uses.

let $datepicker = $('#datepicker');
$datepicker.datepicker({
  duration: 1 // really fast for our purpose here
});

// creates a datepicker element by showing and hiding so we can then walk through
$datepicker.datepicker("show").datepicker("hide");
// back to normal speed for usability
$datepicker.datepicker( "option", "duration", "normal");
$sd =$(".ui-datepicker-calendar").find("[data-date]");
console.log("We have:",$sd.length," Dates in the month, here they are:");
$sd.each(function(){console.log($(this).data("date"));});
.picker-container {
  border: solid 1px blue;
}

.picker-container>tbody {
  display: flex;
}

.picker-day {
  border: solid green 1px
}
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.13.2/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.13.2/jquery-ui.min.js"></script>
<div >
  <p>Date: <input type="text" id="datepicker"></p>
</div>

  • Related