www.webdeveloper.com
Results 1 to 5 of 5

Thread: [RESOLVED] Get selected option for a <select> by <select> id?

  1. #1
    Join Date
    Jun 2012
    Location
    FL, USA
    Posts
    48

    resolved [RESOLVED] Get selected option for a <select> by <select> id?

    So I've got
    Code:
    <select id="timein1">
    and <option value="00:00">00:00</option><option>...etc....</option>
    </select>
    How do I get the selected option's value? I am trying this:

    Code:
    document.getElementById('timein1').onchange = domyfunction();
    
    domyfunction()
    {
    console.log('the function was triggered...');
    console.log(document.getElementById('timein1').option.selected);
    }
    c'mon it's gotta be something easy

  2. #2
    Join Date
    Jun 2012
    Location
    FL, USA
    Posts
    48
    Easy it was. Found the solution:

    Code:
    document.getElementById("myselect").options[0].value //accesses value attribute of 1st option
    document.getElementById("myselect").options[0].text //accesses text of 1st option
    Hope it helps somebody

  3. #3
    Join Date
    Jul 2012
    Posts
    8
    You could do it with jquery which is basically what you are doing


    http://api.jquery.com/selected-selector/


    Code:
    <script>
    
        $("select").change(function () {
              var str = "";
              $("select option:selected").each(function () {
                    str += $(this).text() + " ";
                  });
              $("div").text(str);
            })
            .trigger('change');
    </script>

  4. #4
    Join Date
    Nov 2010
    Posts
    1,082
    from the looks of your question, I don't think you are quite right. What you are getting now is the text and value of the first option in the list, regardless of which option is selected. in plain js you can use this.value and this.options[this.selectedIndex].text

    loading jQuery for this simple task would be overkill

    have a look at the different outputs that you get onchange:

    Code:
    <script type="text/javascript">
    document.getElementById('timein1').onchange = function(){
    console.log(this.options[0].value);
    console.log(this.options[0].text);
    console.log(this.value);
    console.log(this.options[this.selectedIndex].text);
    }
    </script>

  5. #5
    Join Date
    Jun 2012
    Location
    FL, USA
    Posts
    48
    Yeah, thanks. I learned later about this.selectedIndex

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

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



Recent Articles