In this tutorial we will learn how to add additional options to the exiting select box.
Objective: The value typed in a text box would be added to the give selection box by clicking the okey button.
<!DOCTYPE html> <html> <head> <script src="mootools-core-1.4.5-full-compat.js"></script> </head> <body> <form id="myform"> Add this text into <input type="text" id="srctxt" length="12" /> <input type="button" id="addTo" value="Add" /> <select id="target"> <option value="">Please Add</option> </select> </form> </body> <script> window.addEvent('domready', function(){ $('addTo').addEvent('click', function(event){ var textbox= document.id('srctxt'); var selectBox= document.id('target'); var element=new Element('<option>',{'value':selectBox.length+1,'html':textbox.get('value')}); textbox.set({'value':''}); selectBox.add(element); alert('added in the dropdown'); }); }); </script> </html>
In our form we have three elements, the input text ,input button and a target select field with id "target"
which is going to be populated with the value/text given in the input text "srctxt".
Explanation:
In Line 20 we mentioned that , when the button is clicked, the annonymous function executes to do the following.
Get the input text "srctxt" object,get the select box "target" object , and create an element object with option as a tag and value as the length+1 and html whatever the value of the textbox. Finally add this element to the selectBox, and finally show an alert.
Demo: