I have a bootstrap list box containing a number of options. Each option is a medical test and has a value attribute. This value attribute has many values init separated by comma e.g it has Test Name, Test Code and Test Rate, etc. In onchange function of the dual list box, I want to get only Test Rate from all the other values present inside the value attribute.
Note: I cannot put the only Test Rate inside value attribute because I need other values also.
Html Code of my dual list box
<div class="form-group row">
<label class="col-sm-2 text-right col-form-label no-padding-top" for="Test">Test </label>
<div class="col-sm-10">
<select class="form-control" multiple="multiple" size="4" name="test_id" onchange="add_total()" id="duallist">
<% tests.forEach(test => { %>
<option value="<%- test.ID %> , <%- test.Code %> , <%- test.Name %> , <%- test.Type %> , <%- test.TemplateID%> , <%- test.Rate %>"><b><%- test.Code %></b> <%- test.Name %></option>
<% }) %>
</select>
</div>
</div>
Onchange function of the dual list box is bellow. Here I want to get only Test Rate.
function add_total() {
var sum = 0.0;
$('#duallist option:selected').each(function() {
//Want to get only Rate here not the whole value attribute how can I do that
var total = parseInt($(this).attr('value'));
sum = (sum + total);
document.getElementById("subtotal").value = sum;
});
}
In your case, you can separate specific data(Test Rate) from all other data of your value attribute by placing your specific data(Test Rate) inside value2
attribute while all other data remains inside value
attribute as
<div class="form-group row">
<label class="col-sm-2 text-right col-form-label no-padding-top" for="Test">Test </label>
<div class="col-sm-10">
<select class="form-control" multiple="multiple" size="4" name="test_id" onchange="add_total()" id="duallist">
<% tests.forEach(test => { %>
<option value="<%- test.ID %> , <%- test.Code %> , <%- test.Name %> , <%- test.Type %> , <%- test.TemplateID %>" value2="<%- test.Rate %>"><b><%- test.Code %></b> <%- test.Name %></option>
<% }) %>
</select>
</div>
</div>
Now inside onchange function for the dual list box, you can access you specific data(Test Rate) easily as
function add_total() {
var sum = 0.0;
$('#duallist option:selected').each(function() {
var total = parseInt($(this).attr('value2'));
sum = (sum + total);
document.getElementById("subtotal").value = sum;
});
}
All the other data is still available to you inside the value
attribute as you needed so