Codearts Codearts - 5 months ago 11x
HTML Question

JavaScript/jQuery - Get value of span of current element

So I have some

elements and each of its possible options have a price inside span. I loop through all select tags and I need to get the value of the span of the selected option for each of them. So this is my code

<select class="form-control config-option" id="s{{ $availableCategory->index}}">
<option>{{ $availableCategory->default_option }}</option>
@foreach($availableOptions as $availableOption)
@if($availableOption->category->name == $availableCategory->name)
<option>({{ $availableOption->code }}) {{ $availableOption->name }} <span class="option-price">({{ $currency == 'EUR' ? 'EUR' : 'USD'}} {{ $availableOption->price }})</span></option>

I tried to access it via the
function of jQuery by class and by tag name but I fail to do so.

$('.config-option').each(function() {
var currentElement = $(this);
var optionPrice = currentElement.find('.option-price');

If I console log
I get undefined. So how can I access this span? Is there a better way to do it? A solution using plain JavaScript would do as well.


you shouldn't place tags inside option tag, that said try this

$('.config-option').each(function() { 
    var currentElement = $(this);
    var optionPrice = currentElement.find('.option-price').parent().text(); 

updated: span tags get removed by browser so use this markup structure

    <option data-price="PRICE_HERE">

then use this in js

$('.config-option option:selected').each(function() { 
    var optionPrice = $(this).attr('data-price');