Reputation: 3253
Can someone let me know how can I access the values inside the option_value
array? It's an array within another array.
I get the below error with my code:
TypeError: json.option[i].option_value[j] is undefined
My code
$(document).on("click", "[name^='option']", function () {
var value = $(this).val();
var parent_id = $(this)
.attr("name")
.replace(/[^\d.]/g, "");
$.ajax({
url:
"index.php?route=controlller/get_options&parent_id=" +
parent_id +
"&value=" +
value +
"&product_id=<?php echo $product_id; ?>",
type: "get",
dataType: "json",
success: function (json) {
if (json["option"]) {
for (i = 0; i < json["option"].length; i++) {
if (
json["option"][i]["type"] == "radio" ||
json["option"][i]["type"] == "checkbox"
) {
$("#ioption" + json["option"][i]["product_option_id"])
.find("input")
.prop("checked", false);
for (j = 0; j <= json["option"][i]["option_value"].length; j++) {
$("#ioption" + json["option"][i]["product_option_id"])
.find(
"input[value='" +
json["option"][i]["option_value"][j][
"product_option_value_id"
] +
"']"
)
.parent()
.show();
}
}
}
}
},
error: function (xhr, ajaxOptions, thrownError) {
alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
},
});
});
Below is my JSON result:
{
"option": [
{
"product_option_id": "975",
"option_id": "76",
"name": "Stage",
"type": "image",
"option_value": [
{
"product_option_value_id": "2490",
"option_value_id": "389",
"name": "Level 1",
"price": "\u20ac 2,00"
},
{
"product_option_value_id": "2491",
"option_value_id": "390",
"name": "Level 2",
"price": "\u20ac 3,00"
}
],
"required": "1"
}
]
}
Thanks
Upvotes: 0
Views: 54
Reputation: 17366
I don't have an exact structure of your html, but atleast i can provide a clean solution with some Array.map usage.
You can loop through each object and then you can target HTML element you want to.
Example
result.option.map(opt => {
if (opt.type === 'radio' || opt.type === 'checkbox') {
let optionElement = '#ioption' + opt.option_id;
$(optionElement).find('input').prop('checked', false);
opt.option_value.map(optVal => {
let inputElement = 'input[value=\'' + optVal.product_option_value_id + '\']';
$(optionIdElement).find(inputElement).parent().show();
});
}
});
P.S: Snippet won't run as i've not included result json in the answer!
Hope this will help!
Upvotes: 1
Reputation: 295
Get value of option_value use this option[0]["option_value"][0] I just give answer according to display the top json. And 0 replace using any loop(for / foreach) accoding to your requirment.
Upvotes: 0