简体   繁体   中英

Change CSS color from select list option

I'm trying to change css based on a select list options, what am I doing wrong? Help is much appreciated! (I can't change the HTML)

Many thanks.

Erwin

 $("select").change(function() { var color = $("#5f01264e722ae").val(); $("#sw_poster_text2").css("background", color); });
 .sw_poster_text2 { margin: 30px; background: white; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="wapf-field-input"> <select data-is-required="" data-field-id="5f01264e722ae" name="wapf[field_5f01264e722ae]" class="wapf-input"> <option value="">choose an option</option> <option value="0z489" data-wapf-label="black">black </option> <option value="wu4xz" data-wapf-label="brown">brown </option> <option value="5k848" data-wapf-label="blue">blue </option> </select> </div> <div class="sw_poster_text2">My name</div>

Use $(this).find('option:selected').data('wapf-label') to get the value of the select and use . instead of # to select elements with a particular class.

var color = $(this).find('option:selected').data('wapf-label')
$(".sw_poster_text2").css("background", color);

 $("select").change(function() { var color = $(this).find('option:selected').data('wapf-label') $(".sw_poster_text2").css("background", color); });
 .sw_poster_text2 { margin: 30px; background: white; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="wapf-field-input"> <select data-is-required="" data-field-id="5f01264e722ae" name="wapf[field_5f01264e722ae]" class="wapf-input"> <option value="">choose an option</option> <option value="0z489" data-wapf-label="black">black </option> <option value="wu4xz" data-wapf-label="brown">brown </option> <option value="5k848" data-wapf-label="blue">blue </option> </select> </div> <div class="sw_poster_text2">My name</div>

Your option value not is a valid color, you need set a valid color to after set in your style try this:

$("select").change(function() {
  var color = $("#5f01264e722ae").val();
  $("#sw_poster_text2").css("background", color);
});
.sw_poster_text2 {
  margin: 30px;
  background: white;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="wapf-field-input">

  <select data-is-required="" data-field-id="5f01264e722ae" name="wapf[field_5f01264e722ae]" class="wapf-input">
    <option value="">choose an option</option>
    <option value="black" data-wapf-label="black">black</option>
    <option value="brown" data-wapf-label="brown">brown</option>
    <option value="blue" data-wapf-label="blue">blue</option>
  </select>
</div>

<div class="sw_poster_text2">My name</div>

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