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 ).