SitePoint Sponsor

User Tag List

Results 1 to 5 of 5
  1. #1
    SitePoint Member
    Join Date
    Dec 2010
    Posts
    9
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Grab selected text from the <SELECT>

    Hi,

    I am trying to get the value of the selected text from <SELECT> with the follow code

    var gnm = document.getElementById("nm");
    var sval = ngnm.options[ngnm.selectedIndex].text;
    alert(sval);

    but i am getting an error as follows:

    Error Message:
    Line: 129
    char: 2
    Error: Object expected
    Code: 0

    The line 129 belongs to alert(sval);. I do not understand why it is displaying an error for alert?
    Please let me how to grab the selected text from the dropdown menu.
    Thank you for your help in advance.

  2. #2
    om nom nom nom Stomme poes's Avatar
    Join Date
    Aug 2007
    Location
    Netherlands
    Posts
    10,272
    Mentioned
    50 Post(s)
    Tagged
    2 Thread(s)
    You need to post some HTML. Who is "nm"? A form?

    var sval = ngnm.options[ngnm.selectedIndex].text;
    Who is ngnm? You have not introduced him.


    An example of working:
    Code:
    HTML:
    <select id="someSelect">
    ...
    JS:
    var theSelect = document.getElementById('someSelect');
    var selectedOption = theSelect.selectedIndex;
    var selectedOptionText = theSelect.options[selectedOption].text;

  3. #3
    SitePoint Evangelist bals28mjk's Avatar
    Join Date
    Aug 2007
    Posts
    405
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by shirt View Post
    Hi,

    I am trying to get the value of the selected text from <SELECT> with the follow code

    var gnm = document.getElementById("nm");
    var sval = ngnm.options[ngnm.selectedIndex].text;
    alert(sval);

    but i am getting an error as follows:

    Error Message:
    Line: 129
    char: 2
    Error: Object expected
    Code: 0

    The line 129 belongs to alert(sval);. I do not understand why it is displaying an error for alert?
    Please let me how to grab the selected text from the dropdown menu.
    Thank you for your help in advance.
    Did you accidently put an "n" infront of the gnm variable?

    Try

    Code:
    var sval = gnm.options[ngnm.selectedIndex].text;

  4. #4
    om nom nom nom Stomme poes's Avatar
    Join Date
    Aug 2007
    Location
    Netherlands
    Posts
    10,272
    Mentioned
    50 Post(s)
    Tagged
    2 Thread(s)
    Did you accidently put an "n" infront of the gnm variable?
    I wondered the same thing.

  5. #5
    SitePoint Member
    Join Date
    Dec 2010
    Posts
    9
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks you Stomme poes and bals28mjk i was not using the correct id to call the selectedIndex


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
  •