codearts
codearts

Reputation: 2956

JavaScript - Getting value of data attribute returns undefined

So I have a data-time attribute that holds an integer value fetched from my database. I get the value of it but it returns undefined. I inspected the browser and my data-time attribute stores the value correctly. It is really strange because I am doing the same thing before that and it doesn't return undefined. Here is my code:

<option data-price="{{ $availableOption->price * $course }}" data-time="{{ $availableOption->delivery_time }}">
...
</option

Script

$('.config-option option:selected').each(function() {
    var currentElement = $('this');
    var optionDeliveryTimeStr = currentElement.attr('data-time');
    console.log(optionDeliveryTimeStr);
});

I do the exact same thing before that with the data-price attribute and it returns the value as string. But it doesn't work with the data-time attribute. If someone could offer a solution and an explanation I would be very thankful.

Upvotes: 2

Views: 715

Answers (2)

Jayesh Chitroda
Jayesh Chitroda

Reputation: 5039

Use $(currentElement) instead of currentElement:

$('.config-option option:selected').each(function() {
    var currentElement = $(this);
    var optionDeliveryTimeStr = $(currentElement).attr('data-time'); // OR $(currentElement).data('time');
    console.log(optionDeliveryTimeStr);
});

Upvotes: 0

gurvinder372
gurvinder372

Reputation: 68433

Your problem is this line

 var currentElement = $('this');

remove quotes from this and replace it with

 var currentElement = $(this);

Upvotes: 4

Related Questions