letterman549
letterman549

Reputation: 311

sending hidden value with selected optiom

I have a drop down select form that look like this:

<select id="selection">
    <option>try 1</option>
    <option>try 2</option>
    <option>try 3</option>
</select>

I am simply targeting these values like so:

var selected = $('#selection').val();

now how would I go about targeting a hidden value in those options rather than the value between the option tags?

something like:

<select id="selection">
        <option value="selected 1">try 1</option>
        <option value="selected 2">try 2</option>
        <option value="selected 3">try 3</option>
</select>

targeting the value?

Upvotes: 0

Views: 161

Answers (3)

Mukesh Agarwal
Mukesh Agarwal

Reputation: 528

If you want to the value attribute then you can use your same code

var selected = $('#selection').val();

It will return you selected 1

But if you want to get the nodeValue you can use

var selected = $('#selection').val();
var option = $('#selection option');
var selectedValue;
for(var i=0;i<option.length;i++)
{
    if(option[i].value==selected)
    selectedValue = option[i].childNodes[0].nodeValue;
}
console.log(selectedValue)

It will return you try 1

Upvotes: 0

talemyn
talemyn

Reputation: 7960

You need no change at all. The "value" of a select option is always the value attribute, EXCEPT when there isn't one defined. When there is no "hidden value" (i.e., value="some value") set in the HTML, the code will default to the text that is defined for the option.

Using your code, the value of <option>try 1</option> (i.e., has no value attribute) is "try 1", whereas, the value of <option value="selected 1">try 1</option> (i.e., does have a value attribute) is "selected 1".

In fact, the only time that you really need to define a value attribute for a select option is if you need the captured value to be different from what is displayed to the user. For examplei, if you were coding <option value="1">1</option>, you don't actually need the value attribute.

Upvotes: 0

LcSalazar
LcSalazar

Reputation: 16839

The "hidden value" that you are refering to, is actually the value attribute of the option. The one between the tags is the text of the option.

When specified the value attribute, the .val() method from JQuery will already return the correct value.

var selected = $('#selection').val();
alert(selected);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<select id="selection">
        <option value="selected 1">try 1</option>
        <option value="selected 2">try 2</option>
        <option value="selected 3">try 3</option>
</select>

Upvotes: 0

Related Questions