Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

selecting proper value from attribute

I have a select Box for selecting country code :-

<div class="selectWrap">
    <select name="countryCode" id="countryCode"></select>
</div>

It gets populated using javascript and gets options like follows :-

<option data-phone-code="+91">91&nbsp(India)</option>

Now I want to select the value only +91.

I was trying this

var country = document.getElementById("countryCode");
var prefix = country.options[country.selectedIndex].value;

But this returns the Full value with Country.

How can I achieve this ?

like image 540
firebolt_ash Avatar asked May 25 '15 13:05

firebolt_ash


People also ask

How do you select an element by attribute?

The [attribute|="value"] selector is used to select elements with the specified attribute, whose value can be exactly the specified value, or the specified value followed by a hyphen (-). Note: The value has to be a whole word, either alone, like class="top", or followed by a hyphen( - ), like class="top-text".

What are attribute selectors?

The CSS Attribute Selector is used to select an element with some specific attribute or attribute value. It is an excellent way to style the HTML elements by grouping them based on some specific attributes and the attribute selector will select those elements with similar attributes.

What is value attribute in select tag?

The value attribute specifies the value to be sent to a server when a form is submitted. The content between the opening <option> and closing </option> tags is what the browsers will display in a drop-down list. However, the value of the value attribute is what will be sent to the server when a form is submitted.


1 Answers

Use getAttribute, for example:

country.options[country.selectedIndex].getAttribute('data-phone-code');
like image 188
Donal Avatar answered Sep 23 '22 23:09

Donal