简体   繁体   English

jQuery基于多个选择选项显示/隐藏输入

[英]jQuery Show/hide inputs based on multiple select options

I have a drop-down which allows multiple product selection and based on the products selected I want to show inputs for products extra and add a required attribute to those inputs. 我有一个下拉列表,允许多个产品选择,并根据所选产品,我想显示额外产品的输入,并为这些输入添加必需的属性。

 var products = $('#products').select2({ tags: true }); products.on('change', function() { var ids = products.val(); setExtras(ids); }); function setExtras(ids) { $.each(ids, function(index, id) { $('#extras .form-group').each(function() { if ($(this).hasClass('extra_' + id)) { $(this).show('fade').find('input').prop('required', true); } else { $(this).hide('fade').find('input').prop('required', false); } }); }); } 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script> <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6/css/select2.min.css" rel="stylesheet" /> <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6/js/select2.min.js"></script> <div class="form-group"> <label for="products">Products</label> <select multiple="" class="form-control select2" name="products[]" id="products"> <option value="1">Product One</option> <option value="2">Product Two</option> </select> <span class="help-block">Please select your product</span> </div> <div id="extras"> <div style="display: none;" class="form-group extra_1"> <label for="1_1"> Product One(Message) </label> <input type="text" class="form-control" id="1_1" name="extras[1][1]" placeholder="Your message here"> </div> <div style="display: none;" class="form-group extra_2"> <label for="2_2"> Product Two(Message) </label> <input type="text" class="form-control" id="2_2" name="extras[2][2]" placeholder="Your message here"> </div> <div style="display: none;" class="form-group extra_2"> <label for="2_3"> Product Two(Tag Line) </label> <input type="text" class="form-control" id="2_3" name="extras[2][3]" placeholder="Your tag line here"> </div> </div> 

My current JS code only shows inputs for last selected product, please help me out to fix that. 我当前的JS代码只显示最后选择的产品的输入,请帮我解决这个问题。

PS The product extras will be variable, some products has one or more extra and some will have none. PS产品附加功能是可变的,有些产品有一个或多个额外产品,有些产品没有。

You can try change code of function setExtras 您可以尝试更改函数setExtras代码

function setExtras(ids) {
   $('#extras .form-group').each(function () {
      $(this).hide('fade').find('input').prop('required', false);
    });
   $.each(ids, function (index, id) {
    $('#extras .form-group').each(function () {
        if ($(this).hasClass('extra_' + id)) {
            $(this).show('fade').find('input').prop('required', true);
        } 
    });
   });
}

This is a demo link: https://codepen.io/phuongnm153/pen/PvwoZg 这是一个演示链接: https//codepen.io/phuongnm153/pen/PvwoZg

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM