Sign in to follow this  
ManaStone

[web] How do I create a Select Object with javascript?

Recommended Posts

You have to use the createElement function.


/* create a select list element */
var mySelect = document.createElement("select");

/* create some select items */
var myOption1 = document.createElement("option");
myOption1.text = "first item";
myOption1.value = "first"

var myOption2 = document.createElement("option");
myOption2.text = "second item";
myOption2.value = "second"

/* add the items to the list */
mySelect.appendChild(myOption1);
mySelect.appendChild(myOption2);

/* insert the list element (let's assume the page contains a form with id "myForm" */
var myForm = document.getElementById("myForm");
myForm.appendChild(mySelect);

Share this post


Link to post
Share on other sites
Quote:
Original post by ManaStone
Btw, I couldn't find that method on any of the js reference sites I'm visiting. Do you know a website that lists all the functions of specific javascript objects?


I usually use w3 schools. (http://www.w3schools.com/)

Share this post


Link to post
Share on other sites
Quote:
Original post by MortusMaximus
Quote:
Original post by ManaStone
Btw, I couldn't find that method on any of the js reference sites I'm visiting. Do you know a website that lists all the functions of specific javascript objects?


I usually use w3 schools. (http://www.w3schools.com/)


That is what I'm primarily using as well, but it doesn't list the createElement method on its document object page.

Share this post


Link to post
Share on other sites
Quote:
Original post by ManaStone
Quote:
Original post by MortusMaximus
Quote:
Original post by ManaStone
Btw, I couldn't find that method on any of the js reference sites I'm visiting. Do you know a website that lists all the functions of specific javascript objects?


I usually use w3 schools. (http://www.w3schools.com/)


That is what I'm primarily using as well, but it doesn't list the createElement method on its document object page.


The reference you need is here.

Share this post


Link to post
Share on other sites
A nice javascript toolkit (like MooTools) makes life a bit easier (and has easier to follow documentation):

<form id="myForm"></form>

<script type="text/javascript">
window.addEvent('domready', function() {
$('myForm').grab(
new Element('select', {
events : {
change : function() {
alert('You have selected "' + this.value + '".');
}
}
}).adopt(
new Element('option', { text : 'first item', value : 'first' }),
new Element('option', { text : 'second item', value : 'second' })
)
);
});
</script>

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this