Getting Data Attributes on Dynamically Created Select Lists using Javascript

42 Views Asked by At

I have a onchange function on my dynamically created select list which is trying to get the data- attributes but I am getting a "undefined" value.

function changed_option(barcode,id,priceid,price){
  var barcode=barcode;
  var record=id;
  var change_action = ( $(this).find(':selected').data('change_action'));
  var change_amount = ( $(this).find(':selected').data('change_amount'));
  alert("Change Action: "+change_action);
  alert("Change Amount: "+change_action);
}

The HTML generated code is:

<select onchange="changed_option('QKCLASS01NB','1282389738','price_QKCLASS01NB','125.00')"class="form-control col-md-10 center" id="1282389738" required="required" name="attributes[Payment Option]">
<option value="">---Select Option---</option><option data-change_action="0"data-change_amount="0.00">Full Price</option>
<option data-change_action="2"data-change_amount="20.00">Down Payment</option>
</select>

Any help would be greatly appreciated.

2

There are 2 best solutions below

0
Pathik Patel On BEST ANSWER

Here you go.

function changed_option(barcode,id,priceid,price){
  var barcode=barcode;
  var record=id;
  var change_action = ( $('#'+id).find(':selected').data('change_action'));
  var change_amount = ( $('#'+id).find(':selected').data('change_amount'));
  alert("Change Action: "+change_action);
  alert("Change Amount: "+change_amount);
}

Since you are using the onchange event. this will not provide you the reference of your dropdown. You can use the id of ther dropdown to get the seleced value.

0
Alan Friedman On

You can pass this to changed_option to target the correct element.

function changed_option(el, barcode,id,priceid,price){
  var barcode=barcode;
  var record=id;
  var change_action = ( $(el).find(':selected').data('change_action'));
  var change_amount = ( $(el).find(':selected').data('change_amount'));
  alert("Change Action: "+change_action);
  alert("Change Amount: "+change_amount);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select onchange="changed_option(this, 'QKCLASS01NB','1282389738','price_QKCLASS01NB','125.00')"class="form-control col-md-10 center" id="1282389738" required="required" name="attributes[Payment Option]">
<option value="">---Select Option---</option><option data-change_action="0"data-change_amount="0.00">Full Price</option>
<option data-change_action="2"data-change_amount="20.00">Down Payment</option>
</select>