websmentor.com websmentor.com - 2 months ago 23
jQuery Question

Refresh span value and show in alert using jquery

I have dropdown with three options:

soft
,
medium
and
hard
.
onchange
I am showing price in a
span
. When user selects
soft
price is
1000
&
medium
is
1500
, and
hard
is
2000
.

The problem is that my
alert()
is executing before the
span
gets refreshed, but I want to show the
alert
after the price gets refreshed. How can i do this?

<span class="amount"><i class="fa fa-inr"></i>0</span>


$('.support-layer-firmness').on('change', function (e) {
// onchange I am getting old value, if i select soft i am getting 0 instead of 1000
var price = $('span.amount').text();
alert(price);
});


Html

<li class="tmcp-field-wrap">
<label for="tmcp_select_1"></label>
<select class="tmcp-field support-layer-firmness tm-epo-field tmcp-select tm-valid" name="tmcp_select_0">
<option value="Select Firmness_0" class="tc-multiple-option tc-select-option" data-price="">Select Firmness</option>
<option value="Soft_1" class="tc-multiple-option tc-select-option" data-price="1000">Soft</option>
<option value="Medium_2" class="tc-multiple-option tc-select-option" data-price="1500">Medium</option>
<option value="Hard_3" class="tc-multiple-option tc-select-option" data-price="2000">Hard</option>
</select>
<span class="price tc-price hidden">
<span class="amount"><i class="fa fa-inr"></i>1,000</span>
</span>



Answer

jQuery.text method with no argument will return textContent of the element and if argument is set, textContent of the element will be set!

In your example, you never set the textContent of the element, Use jQuery.data to get the data-price value and then use jQuery.text(VALUE) to set the textContent of the element.

$('.support-layer-firmness').on('change', function(e) {
  var price = $(this).find('option:selected').data('price')
  $('span.amount').text(price);
  alert(price);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<li class="tmcp-field-wrap">
  <label for="tmcp_select_1"></label>
  <select class="tmcp-field support-layer-firmness tm-epo-field tmcp-select tm-valid" name="tmcp_select_0">
    <option value="Select Firmness_0" class="tc-multiple-option tc-select-option" data-price="">Select Firmness</option>
    <option value="Soft_1" class="tc-multiple-option tc-select-option" data-price="1000">Soft</option>
    <option value="Medium_2" class="tc-multiple-option tc-select-option" data-price="1500">Medium</option>
    <option value="Hard_3" class="tc-multiple-option tc-select-option" data-price="2000">Hard</option>
  </select>
  <span class="price tc-price  hidden">
	     <span class="amount"><i class="fa fa-inr"></i>1,000</span>
  </span>
</li>