Richard Smith
Richard Smith

Reputation: 11

Display array value of selected option

I am trying to echo a value from an array which includes an id and sku number. I need to echo the sku number of a selected div.

below is a selected div which shows the data-option-type-id

<div class="mageworx-swatch-option text selected" data-option-id="13111" data-option-type-id="166748" data-option-label="3/4" data-option-price="145" style=" max-width: 90px;">3/4"</div>

here is my current code which takes the id and sku from the php array and sends to javascript:

<?php
$_product = $block->getProduct();
foreach ($_product->getOptions() as $o) {
    foreach ($o->getValues() as $value) {
        $result[]=array(
        "itemoption_id" => $value["option_type_id"],
        "itemsku" => $value["sku"]
        );

    }
}
echo json_encode($result);
   ?>
<script type="text/javascript">
// pass PHP variable declared above to JavaScript variable
var result = <?php echo json_encode($result) ?>;
var json = JSON.stringify(result);
document.write(json);
</script>

My mind has hit a wall right now (quite new to this) and any help would be appreciated.

I am thinking along the lines of a javascript if command to see if a div is selected and to match that data-option-type-id to find and display the sku.

I think I would need some ajax in there somewhere?

Would someone be able to point me in the right direction or offer any advice?

Many thanks

Upvotes: 0

Views: 628

Answers (2)

Barmar
Barmar

Reputation: 780724

I recommend making result a JavaScript object rather than array, using the item ID as the keys.

<?php
$_product = $block->getProduct();
foreach ($_product->getOptions() as $o) {
    foreach ($o->getValues() as $value) {
        $result[$value["option_type_id"]]=value["sku"];
    }
}
?>
<script type="text/javascript">
// pass PHP variable declared above to JavaScript variable
var sku_data = <?php echo json_encode($result) ?>;
</script>

You can easily look up the SKU

function get_sku(selected_div) {
    var item_id = selected_div.dataset.optionTypeId; // value of data-option-type-id
    var sku = sku_data[item_id];
    return sku;
}

function show_selected_sku() {
  var selected = document.querySelector(".selected");
  if (selected) {
    let sku = get_sku(selected);
    console.log(sku);
  }
}

Upvotes: 1

Robert
Robert

Reputation: 20286

I don't know about your HTML structure, but definitely, if you want to have JSON object you need to use

 var json = JSON.parse(result);

instead of

 var json = JSON.stringify(result);

parse converts string to JSON and stringify does the opposite

Upvotes: 0

Related Questions