Reading option attribute

28 views
Skip to first unread message

Eddie Shipman

unread,
Mar 2, 2017, 10:15:41 AM3/2/17
to select2
I have a select defined like this:

<select class="form-control" name="QuestionBasicSection.Questions[3].ANSWER_LOOKUP_OPTION_ID" id="QuestionBasicSection.Questions[3].ANSWER_LOOKUP_OPTION_ID" multiple="">
    <option value="57" data-index="1">Child Find/Public Awareness</option>
    <option value="58" data-index="2">Referral</option>
    <option value="59" data-index="3">Assessment/Evaluation</option>
    <option value="60" data-index="4">IFSP Development</option>
    <option value="61" data-index="5">Assistive Technology Services and Devices</option>
    <option value="62" data-index="6">Audiology</option>
    <option value="63" data-index="7">Auditory Services</option>
    <option value="64" data-index="8">Specialized skills training</option>
    <option value="65" data-index="9">Family Counseling</option>
</select>

Using this code, I want to set the $optionscsv text to the values of all the selected option's data-index instead of their val();

var $options = $('#QuestionBasicSection\\.Questions\\[3\\]\\.ANSWER_LOOKUP_OPTION_ID'),
    $optionscsv = $('span#optionscsv');
$("#QuestionBasicSection\\.Questions\\[3\\]\\.ANSWER_LOOKUP_OPTION_ID")
    .select2()
    .on('change', function () {
        $optionscsv.text($options.val());
    });

The result of the code above shows: 57, 59, 60 when Child Find/Public Awareness + Assessment/Evaluation + IFSP Development are selected.
The desired result is: 1, 3, 4



Eddie Shipman

unread,
Mar 2, 2017, 12:47:47 PM3/2/17
to select2
Here is the answer:

.on('change', function () {
    var selected_options = [];
    $(this).find("option:selected").each(function(){
        selected_options.push(parseInt($(this).attr('data-index')));
    });
    $optionscsv.text(selected_options.join());
}); 
Reply all
Reply to author
Forward
0 new messages