Jay Mellow Jay Mellow - 11 months ago 33
HTML Question

Saving several data-attributes to a single variable - If a certain CSS class exists

I'm stuck and could use some help with what I want to accomplish:

When a button is clicked, all data from the data attribute "timebox" gets saved to a single variable. When data is saved, I'd also like to add a "/" as a seperator for each save.

Also, td's without the class "highlighted" should be ignored.

<td class="available highlighted" data-timebox="1 1 26-05-2016 8:0"></td>
<td class="available highlighted" data-timebox="1 1 26-05-2016 8:15"></td>
<td class="available" data-timebox="1 1 26-05-2016 11:30"></td>
<td class="available" data-timebox="1 1 26-05-2016 11:45"></td>
<td class="available" data-timebox="1 1 26-05-2016 12:0"></td>

Does anyone know how to accomplish this in jQuery?
Any help will be appreciated!


I think this solution is pretty straightforward. On the button click, simply grab all elements with the highlighted class that also have a data-timebox attribute, append those values to an array, and then join the array with whatever separator you'd like.

Working Demo

$(function () {
  $("button").on("click", function () {
    var data = [];
    $(".highlighted[data-timebox]").each(function (index, elem){
    data = data.join("/");