phangs
phangs

Reputation: 3

Jquery alert the value of a custom attribute

can somebody please help me in displaying the value of "code" from the dropdown element's attribute. Sorry I am very new to Jquery. Example I want to alert the alue of Afghanistan which whould be 93.

<select name="country" id="country" class="requiredInput" tabindex="5">
<option class="no-op" value="">-- Please select --</option>
<option value="977270" code="93">Afghanistan</option>
<option value="977271" code="355">Albania</option>
<option value="977272" code="213">Algeria</option>
<option value="977273" code="1684">American Samoa</option>
<option value="977274" code="376">Andorra</option>
<option value="977275" code="AO">Angola</option>
<option value="977276" code="AI">Anguilla</option>
<option value="977277" code="AQ">Antarctica</option>
<option value="977278" code="AG">Antigua</option></select>

Upvotes: 0

Views: 701

Answers (5)

geevee
geevee

Reputation: 5451

try:

$('#country').change(function(){
    alert($("option:selected", this).attr('code'));
});

@Satpal suggested a better & faster way, using .find():

$('#country').change(function(){
    alert($(this).find("option:selected").attr('code'));
});

hope that helps.

JsFiddle

However, I would suggest you to use data- prefix attribute. like

<option value="977270" data-code="93">Afghanistan</option>

Then you can use

alert($(this).find("option:selected").data('code'));

Upvotes: 1

Jai
Jai

Reputation: 74738

Better to use custom data-* attribute:

data-code="93"// <----if you can change it like this

then you can get it like this:

$('#country').change(function() {
   var codeVal = $(this).find('option:selected').data('code');
   alert(codeVal);  //----use data here----------^^^^
});

Demo with data-*

or with your current markup:

$('#country').change(function() {
   var codeVal = $(this).find('option:selected').attr('code');
   alert(codeVal);  //----use attr here----------^^^^
});

Demo with attr

Upvotes: 0

xdazz
xdazz

Reputation: 160863

Get the selected option's code by:

var code = $('#country').find(':selected').attr('code');

Upvotes: 0

Rahul
Rahul

Reputation: 2307

You just have to use the Jquery event as::

$("#country").change(function(){
    alert($("#country :selected").attr('data-code'));
})

http://jsfiddle.net/rjha999/6vWWN/

Upvotes: 0

Felix
Felix

Reputation: 38102

I'd suggest you to use data-* instead, for example:

<option value="977270" data-code="93">Afghanistan</option>

then you can do something like this:

$('#country').change(function() {
    var code = $(this).find('option:selected').attr('data-code');
    alert(code);
});

Fiddle Demo

Upvotes: 0

Related Questions