Umar Farooq Aslam
Umar Farooq Aslam

Reputation: 515

How to access the value of a data attribute using jQuery

I want to access the data attribute in jQuery. but every time I try to access it it returns undefined.

code is

<select name="start" id="source">
    <option selected disabled>Select your location</option>
    <option data-lat="74.1833" value="some for php">Gujranwala</option>
    <option data-lat="74.3436" value="some for php">Lahore</option>
    <option data-lat="74.536" value="some for php">sialkot</option>
    <option data-lat="74.0789" value="some for php">gujrat</option>
    <option data-lat="67.0100" value="some for php">Karachi</option>
  </select>

I tried using

$('#source').attr('data-lat');

when user select a option than it should give the custom attribute value. but it is not working.. still get undefined. can anyone show me any alternative solution or if i am wrong in this one please correct it...

try to submit the running example please.. thanks in advance.

if i do any thing wrong explaining the problem, please ignore that, i hope you guys got it what i am trying to say.. :)

Upvotes: 4

Views: 53

Answers (1)

rrk
rrk

Reputation: 15846

You need to target the selected option on which is set custom attribute. By the way, you could use data() function.

$('#source option:selected').data('lat');

Upvotes: 3

Related Questions