Home > OS >  Get custom attribute value from select
Get custom attribute value from select

Time:02-25

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.

CodePudding user response:

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>

CodePudding user response:

this way

const arrayOptions = 
  [...document.querySelectorAll('#sel1 option')]
  .map( opt => `<option value="${opt.id}" `
               `data-custom"${opt.dataset.custom}">`
               `${opt.textContent}"</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>

  • Related