简体   繁体   中英

“data-” attribute as javascript parameter is not working in chrome

HTML:

<select name="employee_ID" id="employee_ID" onchange="$('#IncomeTaxDeduction').val($('#employee_ID').find(':selected').data('incomtax'));"> 
             <option value="" disabled selected style="display:none;">Select</option>          
          <?php foreach ($employee_data as $emp_opt_value): ?>
             <option  value="<?php echo $emp_opt_value['ID']; ?>" data-incomtax= "<?php echo $emp_opt_value['IncomeTaxPercent']; ?>" onclick="deductions(this)" > <?php echo $emp_opt_value['ID']; ?></option>
          <?php endforeach; ?>
</select>

JS:

var itdeduction;

function deductions(obj){
   itdeduction = parseFloat(obj.getAttribute('data-incomtax'));

   alert(itdeduction);
}

This 'data-' attribute works very well in firefox but it is not working in google chrome. Can somebody kindly help me.

Following is the approach to get data attributes is JS:

 <script> function getData() { alert(document.getElementById('sample').getAttribute('data-name')); } </script> <li id="sample" data-name="test">Sample</li> <br/> <button onClick="getData();">Get Attribute Value</button> 

Your code edit:

 <script> var itdeduction; function deductions(){ var element = document.getElementById('employee_ID'); itdeduction = parseFloat(element.options[element.selectedIndex].getAttribute('data-incomtax')); alert(itdeduction); } </script> <select name="employee_ID" id="employee_ID" onchange="deductions();"> <option value="12" data-incomtax= "20">Some Name</option> <option value="13" data-incomtax= "30">Another Name</option> </select> 

What does element.options[element.selectedIndex] do?

It selects the selected option for the select box. example: if somename is selected then element.options[element.selectedIndex] will give us <option value="12" data-incomtax= "20">Some Name</option>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM