JavaScript sets the default option for select

Source: Internet
Author: User

JavaScript sets the default option for select.

can use Selectobj.options[index].selected=true; To set

Selectobj the object of the Drop-down box

Subscript for index Default item

If you cannot determine the default subscript for the number of options, you can use the following method.

This method returns the subscript for the option after the default option is set.

Sets the default option for select and gets the subscript for the option.
Parameter 1: The object of the Drop-down box, parameter 2: The text content of the option
function setselected (selectobj,optionstext) {
for (Var i=0;i<selectobj.options.length;i++) {
if (Selectobj.options[i].text==optionstext) {
Selectobj.options[i].selected=true;
return i;
}
}
}

Of course, the method can also be modified to a selected value to determine the default option.

Example:

<select id= "seletest" Name= "" >
<option value= "0" >a</option>
<option value= "1" >b</option>
<option value= "2" >c</option>
<option value= "3" >d</option>
<option value= "4" >e</option>
</select>

<script>
var Selobj=document.getelementbyid (' Seletest ');
var s2=setselected (selobj, ' d ')
Alert (' s2= ' +s2);
</script>

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.