JS dynamically generates select option code

Source: Internet
Author: User

Sometimes we need to dynamically Add the select option. Below I will separate my work records for you. Here we include jquery and js implementation code.

Js version

The Code is as follows: Copy code

// Create an option
Var newOption = new Option (str, incomeJson. catId, true );
// Obtain the select object
Var diarySelect = document. getElementById ('diarycat _ id ');
// Method 1: Add option to select
DiarySelect [diarySelect. length] = newOption;
// Method 2: Add option to select
DiarySelect. options. add (newOption );
// Change the newly added option to the selected status
DiarySelect. value = incomeJson. catId;

Write as a function

The Code is as follows: Copy code
Function ad_changed (obj)
{
Id = obj. value;
Ajax. call ('adv _ auto. php? Act = get_id & is_ajax = 1', 'parent _ id = '+ id, re_ad_changed, "GET", "JSON ");
}
Function re_ad_changed (result)
{
Child = document. getElementById ('ad _ id ');
Child. options. length = 0;
For (I = 0; I <result. content. length; I ++)
{
Child. options. add (new Option ());
Child. options [I]. value = result. content [I]. ad_id;
Child. options [I]. text = result. content [I]. ad_name;
}
Child. style. display = "";
Return;
}

 

Jquery version

For jquery, we can use the append function, which is very simple.

The Code is as follows: Copy code

$ ("# Diarycat_id "). append ('<option value = "' + incomeJson. catId + '"selected =" selected ">' + str + '</option> ');

The append () method inserts the specified content at the end of the selected element (still inside.

Tip: The tasks executed by the append () and appendTo () methods are the same. The difference is that the content location and selector.

Syntax

$ (Selector). append (content) parameter description

Content is required. Specifies the content to be inserted (including HTML tags ).

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.