How to mark the current option as selected?

I have pages like

index.php?key=toplist&list=magic 

So, if om on this page, for example, I want the Magic option to be marked as selected in the selection menu

 <select name="skill" onchange="window.location.href=this.form.skill.options[this.form.skill.selectedIndex].value"> <option value="index.php?<?=QUERY_STRING?>&list=experience">Experience&nbsp;</option> <option value="index.php?<?=QUERY_STRING?>&list=magic">Magic</option> <option value="index.php?<?=QUERY_STRING?>&list=shielding">Shielding</option> <option value="index.php?<?=QUERY_STRING?>&list=distance">Distance</option> <option value="index.php?<?=QUERY_STRING?>&list=fishing">Fishing</option> </select> 

thanks

+4
source share
3 answers

You add the selected attribute to the option tag. Usually I do it something like this:

 $lists = array('experience', 'magic', 'shielding', 'distance', 'fishing'); foreach($lists as $list) echo "<option value=\"index.php?$QUERY_STRING&list=$list\"" . ($list == $_GET['list'] ? " selected" : "") . ">" . ucfirst($list) . "</option>" 
+6
source

For each <option> you need to check whether the one that should be selected as selected matches the value , and for the one that exists, you should add the selected attribute:

 <option value="..." selected="selected">blah blah</option> 
+3
source

Use selected attribute. In HTML, it will be:

 <option value="x" selected>Label</option> 

And in XHTML it will be:

 <option value="x" selected="selected">Label</option> 

This, by the way, is an HTML question, not a PHP question.

+2
source

Source: https://habr.com/ru/post/1316083/


All Articles