简体   繁体   中英

How to change value based on select item with javascript?

<select id="curr">
          <option value="usd" selected>USD</option>
          <option value="eur">EUR</option>
          <option value="pnd">pound</option>
</select>
 <span class="price" data-usd="$1,500" data-eur="£1.271" data-pnd="€1.000">$1,500</span>
 <span class="price" data-usd="$1,500" data-eur="£1.271" data-pnd="€1.000">$1,500</span>
 <span class="price" data-usd="$1,500" data-eur="£1.271" data-pnd="€1.000">$1,500</span>

I wants if any one choose Eur then price should change to data-eur value.. or whatever they choose that price should update with that data-

You can try something like this:

$('#curr').change(function() {
  var v = $(this).val();
  $("span.price").each(function() {
    $(this).text($(this).attr("data-"+ v))
  })
});

Demo

 $('#curr').change(function() { var v = $(this).val(); $("span.price").each(function() { $(this).text($(this).attr("data-"+ v)) }) });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <select id="curr"> <option value="usd" selected>USD</option> <option value="eur">EUR</option> <option value="pnd">pound</option> </select> <span class="price" data-usd="$1,500" data-eur="£1.271" data-pnd="€1.000">$1,500</span> <span class="price" data-usd="$1,500" data-eur="£1.271" data-pnd="€1.000">$1,500</span> <span class="price" data-usd="$1,500" data-eur="£1.271" data-pnd="€1.000">$1,500</span>

Just write some JS code:

const currencySelector = $("#curr");
const elements = $('.price');
const currencies = {
  'usd': 1500,
  'eur': 1.271,
  'pnd': 1000
}

currencySelector.on('change', (event) => {
const value = event.target.value;
  elements.each((index, el) => {
    $(el).html(currencies[value]);
  });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM