DEV Community

loading...

Robust function to create select tag in javascript

ihavecoke profile image mixbo ・2 min read

Alt Text

Have you feelling write select tag in Javascript is more prolixity, you must insert many option tag in to select tag like this

<select>
  <option value='foo' selected>foo</option>
  <option value='bar'>bar</option>
  ......
</select>

If you need dynamic create select tag options you can write Javascript function like this

function createSelect(options=[['foor',1],['bar',2]]){
  const optionsStr = options.map((ele)=>{
    return `<option value=${ele[1]}>${ele[0]}</option>`
  }).join('')
  return `<select>${optionsStr}</select>`
}

It's ok createSelect can dynamic generate select tag, but if you has more options source like user input, different api response etc here's arguments options must support as many as possible stucture like this

const options = 'foo,bar,baz'
const options = ['foo','bar']
const options = [['foo',1],['bar',2]]
const options = [{id:1, text:'foo'},{id:2, text:'bar'}]
const options = [{value:1, text:'foo'},{value:2, text:'bar'}]
const options = [{value:1, label:'foo'},{value:2, label:'bar'}]

So i just enhancement createSelect function like this

function createSelect(rawOptions){
  let options = []
  if(typeof(rawOptions) === 'string'){
    // 'foo,bar,baz' => ['foo','bar','baz']
    // 'foo#bar,baz.eei' => ['foo','bar','baz','eei']
    options = rawOptions.split(/[.|,|#]/).map((option)=>[option, option])
  }else{
    options = rawOptions
  }
  const optionsStr = Array.from(options).map((option)=>{
    const value = option.id || option.name || option[1] || option[0];
    const label = option.name || option.text || option.label || option[0];
    return `<option value=${value}>${label}</option>`
  }).join('')
  return `<select>${optionsStr}</select>`
}

// demos
const rawOptions='foo,bar'
createSelect(rawOptions) 
// <select>
//      <option value='foo'>foo</option>
//    <option value='bar'>bar</option>
// </select>

const rawOptions=[{id:1, text:'foo'},{id:2, text:'bar'}]
createSelect(rawOptions) 
// <select>
//      <option value='1'>foo</option>
//    <option value='2'>bar</option>
// </select>

const rawOptions=[{value:1, label:'foo'},{value:2, label:'bar'}]
createSelect(rawOptions) 
// <select>
//      <option value='1'>foo</option>
//    <option value='2'>bar</option>
// </select>

....

You can see createSelect function is more robust you can pass any options you want so that use at many case.

Hope it can help you :)

Discussion (0)

pic
Editor guide