Set the default select option in Javascript

Source: Internet
Author: User

Set the default select option in JavaScript.

You can use selectobj. Options [Index]. Selected = true; To set

Selectobj drop-down box object

Index subscript of the default item

 

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

This method also returns the subscript of this option after setting the default option.

 

// Set the default select option and obtain the subscript of the option.
// Parameter 1: the drop-down box object; 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, this method can also be changed to the selected value to determine the default options.

 

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>

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.