0

I'm trying to set the selected option using Javascript literals.

function getHtmlFromTask(task) {
    let markup =        
    `<select class="custom-select d-block" id="stack" value="${task.stack}" required="">
        <option value="">Choose...</option>
        <option value="java">java</option>
        <option value="go">go</option>
        <option value="python">pyhton</option>
        <option value="react">react</option>
        <option value="javascript">javascript</option>
    </select>`
    return markup
}

I'm currently doing the following, but is there a neater way to do this as my list will change over time?

<select class="custom-select d-block" id="stack" required="">
    <option value="">Choose...</option>
    <option value="java"       ${task.stack.match("java") ? 'selected' : ''}>java</option>
    <option value="go"         ${task.stack.match("go") ? 'selected' : ''}>go</option>
    <option value="python"     ${task.stack.match("python") ? 'selected' : ''} >python</option>
    <option value="react"      ${task.stack.match("react") ? 'selected' : ''}>react</option>
    <option value="javascript" ${task.stack.match("javascript") ? 'selected' : ''}>javascript</option>
</select>
ASH
  • 980
  • 1
  • 9
  • 22
  • You could have a function that just builds one `option`, and pass in the value and a selected bool (or do the calculation in the function is it's always based on the value) It's debatable whether that's tidier, but it may make future changes less error prone. – DBS Jan 16 '20 at 11:37
  • yeah, thats not a bad idea. I'll have to get the full list from the server with an api call, but would work, Thanks. – ASH Jan 16 '20 at 11:44

1 Answers1

1

If you separate out the creation of the option elements it may be clearer, here's one possible way you could go about doing that:

function getHtmlFromTask(task) {
    let markup =        
    `<select class="custom-select d-block" id="stack" value="${task.stack}" required="">
        <option value="">Choose...</option>
        ${ buildOption('java', task) }
        ${ buildOption('go', task) }
        ${ buildOption('python', task) }
        ${ buildOption('react', task) }
        ${ buildOption('javascript', task) }
    </select>`
    return markup
}

function buildOption(value, task) {
  return `<option value="${value}" ${task.stack.match(value) ? 'selected' : ''}>${value}</option>`
}
DBS
  • 9,110
  • 4
  • 35
  • 53
  • hmm i never thought to call a function in the literal. I'll try that out thanks :) – ASH Jan 16 '20 at 11:46