JS dynamically generate Select option code

Source: Internet
Author: User
Tags html tags

JS version

The code is as follows Copy Code

Create an option
var newoption = new Option (str,incomejson.catid,true);
Get to select Object
var diaryselect = document.getElementById (' diarycat_id ');
The first option is to add options to the Select
Diaryselect[diaryselect.length]=newoption;
The second option is to add options to the Select
DiarySelect.options.add (newoption);
Let the newly added option become selected
Diaryselect.value=incomejson.catid;

Write a function

  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

jquery We can use the Append function, this 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 Append () and Appendto () methods perform the same tasks. The difference is: the location of the content and the selector.

Grammar

$ (selector). Append (content) parameter description

Content required. Specify what you want to insert (you can include HTML tags).

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.