skip to Main Content

I found a useful jquery code in another topic (Show text based on option selected in dropdown) to show text depending on a dropdown selection.

However, my IDs have spaces and the code doesnt work with that. I don’t have full access to the shopify code / backend to get rid of the spaces (for further clarification: shopify will just use the name of the drop down text as values, hence the spaces)

Could anyone help how to fix the code below?

Thank you so much!!

$('p').hide();
$('#14 Days').show();
$('select').change(function() {
$('p').hide();
  var a = $(this).val();
  $("#" + a).show();
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


<select class="bootstrap-select">
  <option value="14 Days" selected="selected">Feature 1</option>
  <option value="28 Days">Feature 2</option>
</select>
<div>
  <p id="14 Days">Save 25% with the 28 Days size!</p>
</div>
<div>
  <p id="28 Days">Great! You are now saving 25%!</p>
</div>

JS FIDDLE

2

Answers


  1. You can use CSS attribute selectors as another way of selecting elements by id.

    The CSS selector #myId will select the same elements as [id="myId"]. They are practically the same, with the single different of the # selector having greater specificity.

    // So instead of using
    $("#14 days")  // or
    $("#" + a)
    
    // Try using
    $("[id='14 days']")  // and
    $("[id='" + a + "']")
    
    Login or Signup to reply.
  2. I don’t know why you have spaces in you ID. But if it is something that you can’t work around with and absolutely need a solution.

    Change your script as below.

    <script>
    $('p').hide();
    
    var a = $(".bootstrap-select").val();
    $("div > p").each(function(i){
       if(this.id == a){
        $(this).show();
      }
    });
    
    $('select').change(function() {
        $('p').hide();
        a = $(this).val();
        console.log(a);
        $("div > p").each(function(i){
          if(this.id == a){
            $(this).show();
          }
     });
    });
    </script>
    

    Use this instead

    <script>
    var val = $('.single-option-selector').val();
    var sid = val.split(" ").join("_");
    $("#"+sid).css("color","black");
    $(document).ready(function(){
    $('.single-option-selector').change(function(){
      $(".white-hidden-text p").css("color","white");
      val = $(this).val();
      sid = val.split(" ").join("_");
      console.log(sid);
      $("#"+sid).css("color","black");
    });
    });
    </script>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search