1

I know that this might be very simple question and I tried to find solutions in the web but I can't figure it... I have the following C# / ASPX code:

    SelectArea += "<select name=\"Area\" id=\"area\">" + "<option value=\"Default\" style=\"display:none;\">SELECT AREA</option>";
    for (i = 0; i < ds.Tables[0].Rows.Count; i++)
    {
        AreaName = ds.Tables[0].Rows[i]["AreaName"].ToString();
        SelectArea += string.Format("<option value=\"{0}\"/>{0}</option>", AreaName);
    }
    SelectArea += "</select>";

And this javascript function that happeen after submit

function validateProfile() {

    var el = document.getElementById("area").value;
    alert(el);
}

I want some how to get the number of the selected value in the list. I tried with the code above but it doesn't work.

wish for help, thanks!

Nave Tseva
  • 868
  • 8
  • 24
  • 47

3 Answers3

10

For example if you have

  <select id="myselect">
      <option value="1">value1</option>
      <option value="2" selected="selected">value2</option>
      <option value="3">value3</option>
  </select>

To get selected option do:

  var selects = document.getElementById("myselect");
  var selectedValue = selects.options[selects.selectedIndex].value;// will gives u 2
  var selectedText = selects.options[selects.selectedIndex].text;// gives u value2

Sample JsFiddle

Emmanuel N
  • 7,350
  • 2
  • 26
  • 36
  • 1
    Hi, Thank you, but in your JS code I get this error message "cannot read property 'undefined' of undefined", why? – Nave Tseva May 23 '13 at 16:51
  • 1
    To someone who wants to do this easily just do this `let value = document.querySelector('#myselect').value;` – Hail Hydra Jul 10 '17 at 16:13
1

Try with this

var el = document.getElementById("area");
var selectedArea = el.options[el.selectedIndex].value;
Claudio Redi
  • 67,454
  • 15
  • 130
  • 155
0

Try :

var myList = document.getElementById("area");
var selectedValue = myList.options[myList.selectedIndex].value;
var selectedText = myList.options[myList.selectedIndex].text;
hemma731
  • 148
  • 1
  • 1
  • 8
  • Hi, Thanks but I get the error message : cannot read property 'undefined' of undefined why? – Nave Tseva May 23 '13 at 16:53
  • did you put your code in **window.onload** event : window.onload = function() { var myList = document.getElementById("area"); var selectedValue =myList.options[myList.selectedIndex].value; var selectedText =myList.options[myList.selectedIndex].text; alert(selectedText); } With this html code : – hemma731 May 23 '13 at 17:31
  • Now, I didn't put the javascript in Window onload event – Nave Tseva May 23 '13 at 19:54