Virat
Virat

Reputation: 121

Extract value from html select tag using JavaScript

I am getting whole select tag as a value from my code, in order to do work around the value i need to extract the value from my select tag,as this tag is dynamically created by the code.

Below is the value i am getting. How can i extract this using java script.Thanks for your help.

   rowId[0].QValue = "<select id="Type112" class="GridList" rownumber="0" value="Q1 Only" ><option></option><option value="1" selected="selected">Q1 Only</option><option value="2">Q2 Only</option></select>"

Upvotes: 1

Views: 6889

Answers (3)

furkle
furkle

Reputation: 5059

The proper way to do this would be to select the element from the DOM with one of the selection functions. In this case, I prefer document.querySelector:

var type112 = document.querySelector('#type112');

The # means 'id', and you can pass any combination of valid CSS to document.querySelector.

Then, to produce the value of this element, simply call

type112.value

This will give you the text value of the currently selected option within the select element.

Based on your comment, I'm sensing that perhaps you have the text of an element and want to parse out the id? If that's the case, you can try:

var elemString = // whatever your str is
var id = (elemString.match(/id="([^"]+)"/) || [])[0];

This assumes that the id is the first attribute in the string, as well as a whole litany of other things that will probably break in production but will work in the absence of a coherent understanding of what you're trying to do.

Upvotes: 2

Ani
Ani

Reputation: 740

You can simply use the select element id to retrieve the value of the element.

   <select id="Type112" class="GridList" rownumber="0" value="Q1 Only" ><option></option><option value="1" selected="selected">Q1 Only</option><option value="2">Q2 Only</option></select>

You can write the javascript to get the element by id Type112 and so on to get the value:

var s = document.getElementById("Type112");
var selNum = s.options[s.selectedIndex].value;
alert(selNum);

Here's a jsfiddle example

Upvotes: 2

Piyush
Piyush

Reputation: 1162

Try this.

var list = document.getElementById("Type112");
console.log(list.value)
<select id="Type112" class="GridList" rownumber="0" value="Q1 Only" ><option></option><option value="1" selected="selected">Q1 Only</option><option value="2">Q2 Only</option></select>

Upvotes: 0

Related Questions