Thursday, October 8, 2015

Get selected value in dropdown list using JavaScript?

Get selected value in dropdown list using JavaScript?

<select id="ViewBy">
  <option value="1">Subjet1</option>
  <option value="2" selected="selected">Subject2</option>
  <option value="3">Subject3</option>
</select>



Running this code:

var e = document.getElementById("ViewBy");
var strUser = e.options[e.selectedIndex].value;

Would make strUser be 2.
If what you actually want is Subject2, then do this:

var e = document.getElementById("ViewBy");
var strUser = e.options[e.selectedIndex].text;

Which would make strUser be Subject2


--------------------------------------------------------------------------------------------

jQuery:

$("#elementId :selected").text() //the text content of the selected option
$("#elementId").val()            //the value of the selected option

------------------------------------------------------------------------------------------------
AngularJS

// html

<select ng-model="selectItem" ng-options="item as item.text for item in items">
</select>
<p>Text: {{selectItem.text}}</p>
<p>Value: {{selectItem.value}}</p>

// javascript
$scope.items = [{
  value: 'item_1_id',
  text: 'Item 1'
}, {
  value: 'item_2_id',
  text: 'Item 2'
}];

4 comments:

GitHub repository using Git Bash command

  To add a project to a GitHub repository using Git Bash command line, you can follow these steps: Create a new repository on GitHub by logg...