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);
}
});
}
You can set a custom attribute in your
buttonsand set it to theDescriptionvalue like thisI used the custom
data-descriptionattribute to set it to theDescriptionvalue. For more info: https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes