Search code examples
javascriptjquerycssclassonchange

add CSS class on change event


I Have two Select Box with the same class.I am trying to add a class on the change of select option.

HTML:

<select class="selectProduct" name="product_id[]">
  <option value="T-shirt">T-Shirt</option>
 </select>
<input type="text" name="sku[]" placeholder="Code" id ="sku" class="code" />
<input type="text" name="qty[]" placeholder="Qty" id ="qty" class="qty" />

 <select class="selectProduct" name="product_id[]" style="width:400px;">
  <option value="shirt">Shirt</option>
 </select>
<input type="text" name="sku[]" placeholder="Code" id ="sku" class="code" />
<input type="text" name="qty[]" placeholder="Qty" id ="qty" class="qty" />

jQuery:

$(document).on('change', '.selectProduct', function(e) {
  var idSize = $(this).val();
  $(this).find(".code").addClass(idSize);
});

Solution

  • Your select and input is in same hierarchy so use next to get input and add class .

    find search inside the element you give so why your code is fail.

    $(document).on('change', '.selectProduct', function(e) {
      var idSize = $(this).val();
      $(this).next(".code").addClass(idSize);
      $(this).next().next(".qty").addClass(idSize);
    });
    .shirt {
      outline: none !important;
      border: 1px solid red;
    }
    .T-shirt {
      outline: none !important;
      border: 1px solid blue;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <select class="selectProduct" name="product_id[]">
      <option value="T-shirt">T-Shirt</option>
      <option value="shirt">shirt</option>
    </select>
    <input type="text" name="sku[]" placeholder="Code" id="sku" class="code" />
    <input type="text" name="qty[]" placeholder="Qty" id="qty" class="qty" />
    
    <select class="selectProduct" name="product_id[]" style="width:400px;">
      <option value="T-shirt">T-Shirt</option>
      <option value="shirt">Shirt</option>
    
    </select>
    <input type="text" name="sku[]" placeholder="Code" id="sku" class="code" />
    <input type="text" name="qty[]" placeholder="Qty" id="qty" class="qty" />