SitePoint Sponsor

User Tag List

Results 1 to 3 of 3

Hybrid View

  1. #1
    SitePoint Member
    Join Date
    Aug 2007
    Posts
    6
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    accessing the value of a select tag in javascript

    I have written some javascript code to loop through an array of element ids and find them in the document object, using getElementById(). The code is written to validate that all the elements pointed to by the array of ids have been "filled-in" by the client.

    When accessing via HTML, by using Request.Form("NameOfSelectTag"), I can just get the value, like any text input. But accessing it through the DOM seems to be trickier.

    It is easy enough when dealing with input elements (text) but, I am having a difficult time figuring out how to get the value of a select element that has option elements as children. How do I determine which (if any) options was selected?
    Here is the code from my .js file:

    Code:
    function validate(doc, a){
        var s;
        for(var i = 0; i < a.length; i++){
            if(doc.getElementById(a[i]).nodeName == "SELECT"){
                //now that I have found a SELECT item, how do I find out which, 
                //if any, of its options was selected?
            }
            else{//it is a text input
                s = doc.getElementById(a[i]).value;
                if(s.replace(/ /g, "") == ""){
                    //if the text = "" then alert the user to put a value in.
                    //I am doing this part o.k.
    
                }
            }
        }
    }
    Thanks, in advance for any help you can provide.

  2. #2
    I'll take mine raw silver trophy MikeFoster's Avatar
    Join Date
    Dec 2002
    Location
    Alabama, USA
    Posts
    2,560
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Howdy,

    Code:
    sel = doc.getElementById(a[i]);
    
    val = sel.options[sel.selectedIndex].text;
    
    // or loop thru the options array and look for
    
    sel.options[i].selected

  3. #3
    SitePoint Member
    Join Date
    Aug 2007
    Posts
    6
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    that's it.

    Sorry for the delay in responding.

    Your solution is perfect. I somehow missed the selectedIndex attribute of SELECT tag.

    Thanks again.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •