jquery to select option data and value when each dropdown has dynamically created id

I need to auto populate the form based on the dropdown selection. I have multiple dropdown section with dynamic id. How can I use jquery to target dynamic id to get the both option value and data attribute to fill the input text area. I can get the value for predefined id but can’t trigger jquery for unknown id.

@foreach(var number in totalNumber){

  <div class="col-12 col-md-12 col-lg-8 ml-0 pr-1">
 
   <select  name="@number"  class="form-control mb-1">

       <option>Select from the dropdown</option>
         
        @foreach(var product in @Model.ProductList){
          
            <option value="@product.productName"
                    data-pd = "@product.productDescription"
                    data-model = "@product.productModelNo">
                    @product.productName</option>
        }
            
  </select>

  <input type="hidden" class="form-control mb-1" rows="1" placeholder="Product Name"/>

  <input type="hidden"  class="form-control mb-1" rows="1" placeholder="Product description"/>
    
  <input type="hidden" class="form-control mb-1" rows="1" placeholder="Product Model Number"/>
  
 </div>
}

I need to get product Name, product description and product model number on my input field based on the dropdown selection made.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Firstly add some class names to your hidden fields so that they can be easily identified by JQuery.

For example:

<input type="hidden" class="product-name form-control mb-1" rows="1" placeholder="Product Name" />
<input type="hidden" class="product-description form-control mb-1" rows="1" placeholder="Product description" />
<input type="hidden" class="product-model-no form-control mb-1" rows="1" placeholder="Product Model Number" />

Then to set hidden values on changing dropdown, use the change() method. You can find the hidden fields using parent() & find().

As an example:

$('select').on('change', function () {
    var productName = this.value;
    var productDescription = $(this).find('option:selected').data("pd");
    var productModelNo = $(this).find('option:selected').data("model");
    $(this).parent().find(".product-name").val(productName);
    $(this).parent().find(".product-description").val(productDescription);
    $(this).parent().find(".product-model-no").val(productModelNo);
});

Heres a working example https://jsfiddle.net/54equvb0/2/


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x