Home > Software design >  How to loop Options in EJS and not repeating 'selected' like this?
How to loop Options in EJS and not repeating 'selected' like this?

Time:07-13

How to loop Options in EJS and not repeating options every size is chosen? if i add more size, the else if statement must be written again

<% if (size == "s") {%>

 <options value="s" selected>Small</options>
 <options value="m">Medium</options>
 <options value="l">Large</options>

<% } else if (size == "m") {%>

 <options value="s">Small</options>
 <options value="m" selected >Medium</options>
 <options value="l">Large</options>

<% } else if (size == "l") {%>

 <options value="s">Small</options>
 <options value="m">Medium</options>
 <options value="l" selected >Large</options>

<% } %>

CodePudding user response:

use tenary operator

more info here >> https://www.javascripttutorial.net/javascript-ternary-operator/

<options value="s" <%= size == "s" ? "selected" : ""; %>>Small</options>
<options value="m" <%= size == "m" ? "selected" : ""; %>>Medium</options>
<options value="l" <%= size == "l" ? "selected" : ""; %>>Large</options>
  • Related