ClosDesign ClosDesign - 3 months ago 10
HTML Question

Check if the value from JSON response matches a data value on an HTML element

Have a JSON response that I want to match to the value on an HTML element and add a simple string to the HTML element.

Example:
HTML

<div class="product-item" data-mydatavalue="EventOne">Hello this is my div for Event One<span class="maxCapacityForEvent"></span></div>

<div class="product-item" data-mydatavalue="EventTwo">Hello this is my div for Event Two<span class="maxCapacityForEvent"></span></div>


JSON

{"result":[{"EventName":"EventOne","MaxCapacity": 0},{"EventName":"EventTwo","MaxCapacity": 0}]}


I am doing an standard jQuery AJAX call to our service and doing a .each(), looping through the JSON results.
What I want to do is match the EventName value and for each HTML element that the data value matches, to output the MaxCapacity

My jQuery is as follows:

$.ajax({
url: "http://myservice.com/mycall",
type: "GET",
cache: false,
dataType: "json",
success: function (data) {
$.each(data, function (i, eventTypes) {
$.each(eventTypes, function(x, eventType) {
//NEED TO GET THE EVENT NAME FROM SERVICE TO MATCH THIS HTML ELEMENT - HOW DO I DO THIS?
if (eventType.EventName == $('.product-item').data("mydatavalue")){
$('.product-item').data("mydatavalue").find('.maxCapacityForEvent').text(eventType.Available);
}
});
});
},
error: function(xhr, error, data) {
console.log(xhr, error, data);
alert("An error occurred getting the Event Types");


}
});


Here is my JSBin link
JSBIN

Answer

You need to do it like this

$(document).ready(function () {
                $.ajax({
                    url: "service.php",
                    data: data,
                    type: "POST",
                    success: function (response)
                    {
                        $.each(response.result, function (index, event) {
                            console.log(event.MaxCapacity)
                            $(".product-item[data-mydatavalue='" + event.EventName + "']").find('.maxCapacityForEvent').text(event.MaxCapacity);
                        });

                    }
                });
            });

Here is the working fiddle https://jsfiddle.net/hse40g1a/1/