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:
JavaScript
x
6
1
`<select class="form-control" id="editRole">
2
<option value="Editor">Editor</option>
3
<option value="admin">Admin</option>
4
<option value="Super Admin">Super Admin</option>
5
</select>`
6
I tried a way like this and it does not seem to work:
JavaScript
1
9
1
const adminData = {name: John Smith, role: admin};
2
3
`<select class="form-control" id="editRole">
4
${document.querySelector('option[value*="${adminData.role}"]').selected = true}
5
<option value="Editor">Editor</option>
6
<option value="admin">Admin</option>
7
<option value="Super Admin">Super Admin</option>
8
</select>`
9
Advertisement
Answer
You can use the ternary operator.
JavaScript
1
8
1
const adminData = {name: 'John Smith', role: 'admin'};
2
3
const str = `<select class="form-control" id="editRole">
4
<option value="Editor" ${adminData.role === 'editor' ? 'selected' : ''}>Editor</option>
5
<option value="admin" ${adminData.role === 'admin' ? 'selected' : ''}>Admin</option>
6
<option value="Super Admin" ${adminData.role === 'super admin' ? 'selected' : ''}>Super Admin</option>
7
</select>`
8