Fetching the selected value of a 'select' element in JavaScript.

User Generated

Nneba_WL

Programming

Description

I'm currently trying to fetch a value from a 'select' element using JavaScript/JQuery, but for some reason I'm encountering some errors, so I'm obviously not doing it right!

<select id="obejectlistid">

<option selectedID="square">Square </option>

<option selectedID="circle">Circle</option>

<option selectedID="triangle">Triangle</option>

</select>


This is the HTML code I'm using, and the JavaScript code is below. I'm wondering if there's any way to fetch the selected value in a select element (drop down list) using JavaScript/JQuery?

function onAddNewShape() {

var object_list = document.getElementById("objectlist");

var shape = object_list.options[object_list.selectedIndex].value;

alert(shape);

}


User generated content is uploaded by users for the purposes of learning and should be used following Studypool's honor code & terms of service.

Explanation & Answer

Hi here is the working solution for you.

<html>
<head>
<script type="text/javascript">
function onAddNewShape() {


var get_id = document.getElementById("objectlist");
var result = get_id.options[get_id.selectedIndex].value;
alert(result);
}
</script>
</head>
<body>
<select id="objectlist" onchange="onAddNewShape

()">
<option selectedID="square">Square </option>
<option selectedID="circle">Circle</option>
<option selectedID="triangle">Triangle</option>
</select>
</body>
</html>


Anonymous
Just what I needed…Fantastic!

Studypool
4.7
Trustpilot
4.5
Sitejabber
4.4

Similar Content

Related Tags