Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Get custom attribute value from select

I’m trying to clone a select options into another select. At the moment I’m able to do it but now the original option contains a custom attribute. So my question is how can I access to the custom attribute? This is what I have for now:

var options = $('#sel1 option');
var arrayOptions = [];
for (var i = 0; i < options.length; i++) {
    var id = parseInt($(options[i]).val(), 10);
    var text = $(options[i]).text() || '[select a type]';
            
    arrayOptions.push('<option value="' + id + ' data-custom="' + options[i]["data-custom"] + '">' + text + '</option>');
    
}
console.log(arrayOptions);

<select id="sel1">
    <option value="1" data-custom="abc1">Hello 1</option>
    <option value="2" data-custom="abc2">Hello 2</option>
    <option value="3" data-custom="abc3">Hello 3</option>
</select>

Right now options[i]["data-custom"] is setting undefined instead of abc1, abc2, etc.

Here is a fiddle.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can use dataset.custom

var options = $('#sel1 option');
var arrayOptions = [];
for (var i = 0; i < options.length; i++) {
    var id = parseInt($(options[i]).val(), 10);
    var text = $(options[i]).text() || '[select a type]';
                
    arrayOptions.push('<option value="' + id + ' data-custom="' + options[i].dataset.custom + '">' + text + '</option>');
}
$('#result').text(arrayOptions.join("\n"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="sel1">
<option value="1" data-custom="abc1">Hello 1</option>
<option value="2" data-custom="abc2">Hello 2</option>
<option value="3" data-custom="abc3">Hello 3</option>
</select>
<pre id="result"></pre>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading