0

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


Accepted answer

But I need to know how to see if the element has a datavalue but does not exist in the JSON response. But I am getting an all or nothing.

My current JS

 $.ajax({
            url: url,
            type: "GET",
            cache: false,
            dataType: "json",
           },
            success: function (data) {
                $.each(data.result, function (i, eventTypes) {
           $('.product-item').each(function () {
                           if ($(this).attr('data-mydatavalue') == eventTypes.EventName) {
                                     $(this).find('.maxCapacityForEvent').html(eventTypes.Available);
                           } else{
//This is giving filling in all elements with No Available if one of the
//.product-item elements don't have a data value.      
                       $(this).find('.maxCapacityForEvent').html("Not Available");
                           }
                        });
   });
3
  • Can you create a JS fiddle of this? It'll help people answer the question jsfiddle.net Commented Sep 9, 2016 at 15:53
  • Your need to right like this to select div element with a specific data value if ($(".product-item[data-mydatavalue='"+eventType.EventName+"']")) { $(".product-item[data-mydatavalue='"+eventType.EventName+"']").text(eventType.Available); } Commented Sep 9, 2016 at 16:25
  • api.jquery.com/attribute-equals-selector Commented Sep 9, 2016 at 16:58

2 Answers 2

2

You can do this easily without having to iterate over the eventTypes.

Here is an example.

function doIterateJSON() {
  var json = '[{"EventName":"EventOne","MaxCapacity": 0},{"EventName":"EventTwo","MaxCapacity": 0}]';
  $.each($.parseJSON(json), function(key, value) {
    $('.product-item').each(function() {
      if ($(this).attr('data-mydatavalue') == value.EventName) {
        $(this).find('.maxCapacityForEvent').html(value.MaxCapacity);
      }
    });
  });
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<button onclick="javascript:doIterateJSON();">
  YEAH DO IT!
</button>

<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>

Sign up to request clarification or add additional context in comments.

5 Comments

Later on, if someone changes the data using data('mydatavalue', 'new value'), the .attr('data-mydatavalue') will fail to pick up the change.
@MikeMcCaughan I actually have no idea about data(). I think i should RTFM before I should answer. Or maybe you can contribute to my answer, I would be really grateful :D
Up voted for getting me on the right track. Found my solution with your technique.
@Jay, I posted an update about a question using the IF statement that if there is an element in the HTML of the page but the JSON result does not contain a value. In my ELSE statement, all of the elements on the page get a "No Available" text if I use the ELSE statement. Any ideas on this?
@ClosDesign lets discuss this in chat
1

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);
                            });

                         $(".maxCapacityForEvent").each(function () {
                            if ($(this).html() === '')
                            {
                               $(this).html("Not Available");
                            }
                         });

                    }
                });
            });

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

3 Comments

I like this answer better, using my same AJAX call as I am.
Posted an additional question for non existent values but the HTML has an element on the page that does not match any values in the response.
Many approach to do that. One can be to check for empty span after loop finish and set their text/html to Not available. Check updated fiddle jsfiddle.net/hse40g1a/4

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.