JSFiddle - React, Tailwind, and code Playground

by Larry D'Almeida

HTML

<!-- some content of a product page that is dynamically 
refreshed via AJAX -->

<div class="product-attr">

   <div class="product-attr__color" data-error='false'>
     <label for="color">
       Color: 
       <span class="product-attr__error">Please select a color!</span>          </label>
     <select id="color">
       <option value="-1">Select color</option>
       <option value="red">red</option>
       <option value="red">red</option>
       <option value="red">yellow</option>
       <option value="red">blue</option>
     </select>
   </div>  <!-- /color -->
   
   
   <div class="product-attr__size">
     <label for="size">Size:</label>
     <select id="size">
       <option value="s">S</option>
       <option value="m">M</option>
       <option value="l">L</option>
     </select>
   </div>  <!-- /size -->

</div>  <!-- /product-attributes -->

CSS

.product-attr {
  
  .product-attr__color,
  .product-attr__size {
    label,
    select {
      font-size: 12px;
      
      option {
        font-size: 10px;
      }
    }
    
    .product-attr__error {
      display: none;
      color: red;
      
      &.show {
        display: inline-block;
      }
    }  //.product-attr__error
    
  } //.product-attr__color, .product-attr__size
  
}  //.product-attr

JavaScript

$(function() {
	
  //this works fine the first time before the AJAX call in the handler function but after the content is refreshed it doesn't work!
	$('#color').on("change", function() {
  
    if($('#color').find(":selected").val() == -1) {
    	//show error
    	$('#color').parent().find('label .product-attr__error').addClass('show');
      
      $('#color').parent().data('error', true);
    } else {
    
    	//no error
    	//AJAX call to refresh content and updated content in 'product-attr' div
    }
    
  });
  
});