Suppose we've a drop down menu like this
<select name="op" >
<option value="1">A</option>
<option value="2">B</option>
<option val开发者_运维问答ue="3">C</option>
</select>
Now, I need to specify that option with value "2" should be the default (I only know this when the page is being called so can't hardcode the default value) Am I correct that I need to get above code segment turned (at runtime) into something like
<select name="op" >
<option value="1">A</option>
<option selected value="2">B</option>
<option value="3">C</option>
</select>
or is there a better/ easier way for which one won't need to iterate through each of the option value comparing and if a match is found adding the "selected" part in that line?
No, that's it. But usually
- Your list of values will be dynamic as well, and you'll have to iterate through it to generate your HTML options anyway
You'll use some web framework which will provide JSP tags and/or UI components handling this for you. Your code will then look like this:
<s:select name="op"> <s:options optionsCollection="${actionBean.theOptions}" value="id" label="name"/> </s:select>
you can set default value at runtime using javascript and JQuery like this:
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquerylatest.js"></script>
<script>
$(document).ready(function(){
$('select[name=op] option[value=2]')attr('selected', 'selected');
});
</script>
</head>
<body>
<select name="op">
<option value="1">A</option>
<option value="2">B</option>
<option value="3">C</option>
</select>
</body>
</html>
but one thing makes me wonder. if it is "written like static html code segment" as you stated why setting the default value at runtime?
精彩评论