Code summary for jquery to operate select option

Source: Internet
Author: User

1. Obtain the selected select value and text. The html code is as follows:
Copy codeThe Code is as follows:
<Select id = "mySelect">
<Option value = "1"> one </option>
<Option value = "2"> two </option>
<Option value = "3"> three </option>
</Select>

You can use the following script code s to obtain the selected value and text
Copy codeThe Code is as follows:
$ ("# MySelect"). val (); // obtain the value of the selected record
$ ("# MySelect option: selected"). text (); // obtain the text value of the selected record

2. Use the new Option ("text", "value") method to add option
Copy codeThe Code is as follows:
Var obj = document. getElementById ("mySelect ");
Obj. add (new Option ("4", "4 "));

3. Delete All option options
Copy codeThe Code is as follows:
Var obj = document. getElementById ("mySelect ");
Obj. options. length = 0;

4. delete option
Copy codeThe Code is as follows:
Var obj = document. getElementById ("mySelect ");
Var index = obj. selectedIndex;
Obj. options. remove (index );

5. Modify the option
Copy codeThe Code is as follows:
Var obj = document. getElementById ("mySelect ");
Var index = obj. selectedIndex;
Obj. options [index] = new Option ("three", 3); // change the corresponding value
Obj. options [index]. selected = true; // keep selected

6. Delete select
Copy codeThe Code is as follows:
Var obj = document. getElementById ("mySelect ");
Obj. parentNode. removeChild (obj); // remove the current object

7. select selected RESPONSE event
Copy codeThe Code is as follows:
$ ("# MySelect"). change (function (){
// Add the operation code to be executed
})

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.