skip to Main Content

We are displaying JOSN in a for each loop and adding the data to some html.

$.ajax({
  dataType: "json",
  url: 'https://***************************',
  success: function (data) {
    var html = '<div class="row">';
    $.each(JSON.parse(data), function (index, value) {
      html += '<button onclick="storeVar(this);" value="' + value.ItemCode + '" type="button" data-bs-toggle="modal" data-bs-target="#staticBackdrop" class="btn btn-outline-fleet"><i class="fa-solid fa-up-right-from-square pe-1"></i>Check Stock</button></div>';
    });
    html += '</div>';
    $('#output').html(html);
  }
});

Each button is storing the value what is referred to as ItemCode.

JSON DATA

 "[
    {"ItemCode":"123abc","Description":"example1"},
    {"ItemCode":"abc123","Description":"example2"}
    ]"

JS

function storeVar(el) {
  var ffref = el.getAttribute('value'); 
  **var selected-description = GET THE DESCRIPTION FOR THE ITEM-CODE OF THE CLICKED BUTTON VALUE AND STORE IT AS A VARIABLE**
} 

When the button is clicked it stores the value (what is the ItemCode) to the variable ffref.

We want to get the Description that is equal to the ItemCode but cannot figure out how to do this

Attempt:

function storeVar(el) {
  var ffref = el.getAttribute('value');

  $.ajax({
    dataType: "json",
    url: 'https://********************',
    success: function (data) {
      var json = [];
      var resObj = JSON.parse(data);
      for (var key in resObj) {
        if (resObj[key].ItemCode == ffref) {
          json.push(resObj[key]);
        }
      }
      alert(json);
    }
  });
}

2

Answers


  1. You can set a custom attribute in your buttons and set it to the Description value like this

    var data = [
        {"ItemCode":"123abc","Description":"example1"},
        {"ItemCode":"abc123","Description":"example2"}
    ];
    
    var html = '<div class="row">';
    $.each(data, function (index, value) {
        html += '<button onclick="storeVar(this);" value="' + value.ItemCode + '" type="button" data-description="'+value.Description+'" data-bs-toggle="modal" data-bs-target="#staticBackdrop" class="btn btn-outline-fleet"><i class="fa-solid fa-up-right-from-square pe-1"></i>Check Stock</button>';
    });
    html += '</div>';
    $('#output').html(html);
    
    function storeVar(el){
      var ffref = el.getAttribute('value');
      var description = el.getAttribute('data-description');
      console.log(description);
    } 
    <div id="output">
    
    </div>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>

    I used the custom data-description attribute to set it to the Description value.
    For more info: https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes

    Login or Signup to reply.
  2. I would always suggest an implementation which somehow separates the created markup from the event- and the data-handling.

    As for the OP’s problem, I would use a helper function which generates the markup of a single button. There I would utilize a custom data-* global attribute which for the provided data could be named e.g. data-item-id and would get/have assigned the value of an item-data’s ItemCode property.

    The parsed json-value is a list of such items. And since each item features its unique ItemCode identifier-key, I suggest the creation of an ItemCode-key based Map instance as lookup-table. The advantage is the direct relationship of an item’s stored data and its id which is part of any button’s custom data-attribute. In case the entries of a data-item are going to be increased or their naming has been changed, one does not need to reflect these changes as additional data-properties of an item’s related button. The id is always enough.

    And the event-handling should be based on event-delegation. Thus, one does subscribe just a single handler to all of the buttons’ common parent-node. This handler ensures for each click that the event-target is always a button element. Since it in addition of knowing the currently clicked button element also lays within the scope of the data-lookup, it can easily pass the item related id and the lookup-reference with a forwarding call to the OP’s data-storage handler-function.

    // the json value retrieved from th API call.
    const jsonValue =
      '[{"ItemCode":"123abc","Description":"example1","additionalKey":"additional value"},{"ItemCode":"abc123","Description":"example2","otherKey":"other value"}]';
    
    createAndEnableItemButtons($('#output'), jsonValue);
    body { margin: 0; }
    .as-console-wrapper { min-height: 85%!important; bottom: 0; }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    <script>
    function handleDataStorage(itemId, lookup) {
      const { Description: description } = lookup.get(itemId);
    
      console.log({ description });
    }
    
    function createButtonMarkup({ ItemCode }) {
      return `
        <button type="button" data-item-id="${ ItemCode }" class="btn btn-outline-fleet">
          <i class="fa-solid fa-up-right-from-square pe-1"></i>
          Check Stock
        </button>`;
    }
    
    function createAndEnableItemButtons($root, jsonValue) {
      // data handling.
    
      const dataList = JSON.parse(jsonValue);
    
      // create an `ItemCode` based map for fast lookups.
      const dataLookup = new Map(
        dataList.map(({ ItemCode, ...restData }) => [ItemCode, restData])
      );
    
      // just in order to show how a key-based lookup-table could look like.
      console.log({
        dataById: Object.fromEntries([...dataLookup.entries()]),
        dataList,
      });
    
      // event-delegation based event-handling and markup creation.
    
      const $parent = $('<div class="row"/>');
    
      // - event delegation ... part 1 ... a single handler at the parent node.
      $parent[0].addEventListener('click', ({ target }) => {
      
        // - event delegation ... part 2 ... always ensure an HTMLButton element.
        if (target = target.closest('button')) {
    
          // - forwarding to the data storage handler.
          handleDataStorage(target.dataset.itemId, dataLookup);
        }
      });
    
      $parent.html(
        dataList
          .reduce((markup, data) => {
    
            return markup + createButtonMarkup(data);
    
          }, '')
      );
      $root.append($parent);
    }
    </script>
    
    <div id="output"></div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search