Alexandre Jaquet wrote:
Hi,
I'm looking for the shortest way to write :
if (form.interface_template.options.length > 0) {
template =
form.interface_template.options[form.interface_template.selectedIndex].value
} else {
template = ''
}
There are two things you can do:
Use a variable to store a reference to the form element, it will save
lookups and therefore be faster (but you may not notice the couple of
clock cycles shaved from the execution time if it's a one-of :-) ).
Reduce code bloat. The value of a select is the value of the selected
option, and the value of the selected option is that of the value
attribute, or if it conforms to the W3C spec and doesn't have one,
the content (text). In the case of IE, it must have a value
attribute or 'value' will return an empty string.
<URL:http://www.w3.org/TR/html4/interact/forms.html#edef-SELECT>
Presuming that 'form' is a reference to a form on your page, and that
'interface_template' is the name of a select element in 'form' and
that an option is selected (you should always set one to selected)
and it has a value attribute:
var template;
var t = form.interface_template;
(t.options.length > 0)? template = t.value : '';
will do the trick - though I don't understand what the significance
of testing how many options there are. If there are none, the value
of the select will be empty or ''. Incidentally, that would be
invalid HTML.
So you may as well just write:
var template = form.interface_template.value;
Some play code:
<form action="">
<select name="sel">
<option value="one" selected>one</option>
<option value="two" >two</option>
<option value="three">three</option>
<option value="four" >four</option>
</select>
<br>
<input type="button" value="Selected value" onclick="
alert(this.form.sel.value);
">
</form>
--
Rob