javascriptcustom-data-attributeselectlist

Getting Data Attributes on Dynamically Created Select Lists using Javascript


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.


Solution

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