I am creating an admin panel. On this admin panel, Super Admins will be able to edit other admins’ roles. On the edit screen I have a dropdown that contains the available roles an admin can have. I am using a template literal to inject this HTML into a modal of my own design. My issue is, I am not sure how I can dynamically select the option that contains the value of the Admin’s role saved in the database.
For example, if the JSON of admin data is like this { name: John Smith, role: admin }
how could I select that in a template literal like this automatically:
`<select class="form-control" id="editRole"> <option value="Editor">Editor</option> <option value="admin">Admin</option> <option value="Super Admin">Super Admin</option> </select>`
I tried a way like this and it does not seem to work:
const adminData = {name: John Smith, role: admin}; `<select class="form-control" id="editRole"> ${document.querySelector('option[value*="${adminData.role}"]').selected = true} <option value="Editor">Editor</option> <option value="admin">Admin</option> <option value="Super Admin">Super Admin</option> </select>`
Advertisement
Answer
You can use the ternary operator.
const adminData = {name: 'John Smith', role: 'admin'}; const str = `<select class="form-control" id="editRole"> <option value="Editor" ${adminData.role === 'editor' ? 'selected' : ''}>Editor</option> <option value="admin" ${adminData.role === 'admin' ? 'selected' : ''}>Admin</option> <option value="Super Admin" ${adminData.role === 'super admin' ? 'selected' : ''}>Super Admin</option> </select>`