creat a textfield using dom

Discussion in 'JavaScript' started by srdva59, Aug 4, 2010.

  1. #1
    hi,
    i need creat some elements for example textfield and a combolist
    using dom.
    what i find so far was very complex examples that don´t do what i need
    that is only creat a text field and a combolist with custum values inside.
    any one can help me?
    thanks a lot for your help :)
     
    srdva59, Aug 4, 2010 IP
  2. camjohnson95

    camjohnson95 Active Member

    Messages:
    737
    Likes Received:
    17
    Best Answers:
    0
    Trophy Points:
    60
    #2
    Hope this helps:
    
    <script type="text/javascript">
        //the textbox is easily done
        
        var tb = document.createElement("input");    //create a new element
        
        //assign it's properties
        tb.id = "txt1";    
        tb.type = "text";
        tb.value = "My textbox";
        
        //add the element to document body, you can add it to a div or anything really
        document.body.appendChild(tb);       
        
        
        //A dropdownlist is a little bit more difficult
        //The easiest way is to store the options and values in arrays
        
        var opts = ["Red","Green","Blue"];       //options as they are displayed
        var vals = ["R","G","B"];                //values of corresponding items
        
        var sel = document.createElement("select");   //create the element 
        sel.id = "dropdownlist1";
        var opt;  //we'll use this shortly
        
        for(i=0; i<opts.length; i++) {          //loop through each value in the array
               opt = document.createElement("option");      //create a new option
               opt.innerHTML = opts[i];     //assign what it will display
               opt.value = vals[i];         //assign it's value
               sel.appendChild(opt);        //add it to our dropdownlist
               //this repeats for each item in the array
        }
        
        //now we just add our dropdownlist which consists of all our options to the document.
        //once again this can be added to a div or other element.
        document.body.appendChild(sel);
    </script>
    
    Code (markup):
     
    camjohnson95, Aug 5, 2010 IP