2

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.

0

2 Answers 2

4

Your problem is this line

 var currentElement = $('this');

remove quotes from this and replace it with

 var currentElement = $(this);
Sign up to request clarification or add additional context in comments.

3 Comments

Yes it did. I have it correctly with data-price but didn't notice I wrote quotes with the second data attribute.
Also consider jQuery has a another method for getting data atts .data('time').
@Andy many time this data method doesn't work especially when this attribute is set dynamically at later stage than element creation. So, I would rather suggest to keep it simply since OP hasn't mentioned how this attribute is created.
0

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);
});

1 Comment

$(currentElement).attr('data-time'); == $($(this)).attr('data-time'); ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.