Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to match JSON with Data Attribute on Multiple Button Onclick

I need a little help with trying JSON, data-attributes and onclick HTML functions.

I have a bottom menu with a list of "badge" buttons with "data-day" attributes (1,2,3...), and a library of cards on top which I fetch from a JSON data file.

Every time a user click on a badge button, I would like JS to fetch the corresponding JSON category so that (JSON) "day": n === "data-day= n" (HTML).

So there are mainly two things to add to this code:

  1. Have the JSON value cardlibrary.cards[i].day match with the HTML data attribute data-day (which I left a 1 value for now),
  2. Add an onclick trigger function on every "badge" button to refresh the card library data when a button is selected.

If there are better ways at going about this, I'm open to suggestions! (I'm new to JS/JSON so my knowledge is quite limited).

Thanks in advance!

var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if(xhr.readyState === 4 && xhr.status === 200) {
  var cardlibrary = JSON.parse(xhr.responseText);
  var statusHTML = '<ul class="libraryCard-container">';
  
  for (var i=0; i<cardlibrary.cards.length; i ++) {
    
    //If selected card data is equal to a data attribute 
    if (cardlibrary.cards[i].day === 1)) {
      statusHTML += '<li><h3>';
      statusHTML += cardlibrary.cards[i].title;
      statusHTML += '</h3></li>';
    } 
    
  } // end for loop

  statusHTML += '</ul>';
  document.getElementById('libraryList').innerHTML = statusHTML;
}
};
xhr.open('GET', 'js/json/cards.json');
xhr.send();


//From separate cards.json file
{
  "cards": [{
      "day": 1,
      "title": "The Netherlands",
    }, {
      "day": 1,
      "title": "Germany",
    }, {
      "day": 2,
      "title": "France",
    }
}
<!-- Cards Library corresponding to selected Badge below -->
<div id="libraryList"></div>

<!-- Badges Menu beneath the card library-->
<div class="badgeLibrary">
  <ul>
    <li><button class="badge" data-day="1"></li>
    <li><button class="badge" data-day="2"></li>
    <li><button class="badge" data-day="3"></li>
  </ul>
</div>
like image 631
Issey Avatar asked May 31 '26 08:05

Issey


2 Answers

first,i think you should add a event listener for badge button: code:

document.getElementsByClassName('badgeLibrary')[0].onclick = function(e){
    var target = e.target;
    if (target.tagName == 'BUTTON') {
      var dataDay = target.getAttribute('data-day');
      obtainData(dataDay);//send request
    }
  }

then i package you xhr to a function: code:

function obtainData(dataDay){
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function () {
    if(xhr.readyState === 4 && xhr.status === 200) {
    var cardlibrary = JSON.parse(xhr.responseText);
      var statusHTML = '<ul class="libraryCard-container">';

      for (var i=0; i<cardlibrary.cards.length; i ++) {

        //If selected card data is equal to a data attribute
        if (cardlibrary.cards[i].day == dataDay) {
          statusHTML += '<li><h3>';
          statusHTML += cardlibrary.cards[i].title;
          statusHTML += '</h3></li>';
        }

      } // end for loop

      statusHTML += '</ul>';
      document.getElementById('libraryList').innerHTML = statusHTML;
    }
    };
    xhr.open('GET', 'js/json/cards.json');
    xhr.send();
  }
like image 192
JKong Avatar answered Jun 02 '26 20:06

JKong


Here is your example,

this app using jquery and dot.js for render data from json in buttons with data-id.

<html>
    <head>
        <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/dot/1.1.0/doT.js"></script>

    </head>
    <body>
            <div id="container"></div>

            <!-- Template Javascript - HTML !-->
            <script id="templateButtons" type="text/x-dot-template" >
                {{~it.detalle :value:index}}
                <button class='button' data-id="{{=value.id}}">Button {{=value.id}} </button>
                {{~}}
            </script>

            <script>
              // on ready document in jquery
                $(function() {

                  // json data
                    var data =  [
                        {
                            "id": 0,
                            "title": "The Netherlands"
                        }, 
                        {
                            "id": 1,
                            "title": "Germany"
                        }, 
                        {
                            "id": 2,
                            "title": "France"
                        }
                    ];

                 // Render Template
                    // Get HTML from Template in Jquery
                    var template = $("#templateButtons").html();
                    // Generate HTML for all rows in json
                    var html = doT.template(template)({detalle:data});
                    // Put HTML in container div
                    $("#container").html(html);

                    // Event for buttons
                    $(".button").click(function() {
                        // Get data id
                        var id = $(this).data("id");
                        // show text for json id
                        alert("this is:" + data[id].title);
                    });


                });            
            </script>
    </body>


</html>

I hope with this example you understand how to program your app

like image 37
Jorge Londoño Avatar answered Jun 02 '26 20:06

Jorge Londoño



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!