0

I am looking to reference some JSON variables on page load. Based on a value being true/false, append a class to an html element.

Can't getting this to work, would appreciate some help - being new to jquery and all.

// html
<form id="add_form">
<script type="application/json" data-type="product"
{"product_options": [
{"sku": "ABC123", "price": "$10", "in_stock": true, "can_order": true, "option1": "Small"},
{"sku": "DEF456", "price": "$20", "in_stock": false, "can_order": false, "option1": "Medium"}], "id": 31, "name": "Some Shirt style"}
</script>...</form>

I'd like to iterate through the elements of the .size_options class and add a class to the li element based on the "in_stock" value in the JSON; i.e. if the value is true, add a class.

// parse JSON data
var obj = JSON.parse($("#add_form script[type='application/JSON']").html());

$(".size_options li").each() {
    some code
});

I'd appreciate any help here.

4
  • You'll need some way to get the id from the li element. Would that be possible? Commented Nov 20, 2015 at 7:08
  • You'll need a way to match up each product_options element with each .size_options li element and use .addClass(...) Commented Nov 20, 2015 at 7:08
  • dynatable.com Commented Nov 20, 2015 at 7:13
  • In a task like this I would use AngularJS, it simplify many things when working with JSON and manipulating the DOM Commented Nov 20, 2015 at 7:23

2 Answers 2

1

In this case number of li and length of obj.product_options should be equal.

$(".size_options li").each(function (index) {
    if (obj.product_options[index].in_stock) {
        $(this).addClass("classToBeAdd");
    }
});
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! Works perfectly.
0

You need to append a data-attribute as 'data-can_order' with the same JSON value, then iterate the element and according to the True value append a class.

But i will suggest prior to check the 'in_stock' attribute with the 'can_order', then append the class.

Comments

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.