[英]How to show/hide div based on selected Multiple value in select2 jQuery field
I have select2 jquery dropdown which compose of two items *For Rent *For Sales If i selected For Rent a certain fields will be displayed under it same as the For sales. 我有由两个项目组成的select2 jquery下拉列表*用于出租*用于销售如果我选择了用于出租,则某些字段将显示在其下方,与“用于销售”相同。 The problem is i don't know how i'm gonna display both fields if user selected both in dropdown. 问题是我不知道如果用户在下拉列表中选择了两个字段,我将如何显示两个字段。
In my code I tried to do it but when user selected just only one it displays both fields 在我的代码中,我尝试执行此操作,但是当用户仅选择一个时,它将显示两个字段
$('#for_sales_fields').hide();
$('#for_rents_fields').hide();
$('#property-types-ids').change(function() {
if($(this).val() == 1) {
$('#for_sales_fields').show();
}
else {
$('#for_sales_fields').hide();
}
if($(this).val() == 2) {
$('#for_rents_fields').show();
}
else {
$('#for_rents_fields').hide();
}
var test = [];
$.each($('#property-types-ids :selected'), function(){
test.push($(this).val());
$('#for_sales_fields').show();
$('#for_rents_fields').show();
})
}
);
Here is the solution for your problem: 这是您的问题的解决方案:
Initially, you need to keep both div hidden, in change event. 最初,在更改事件中,您需要将两个div都隐藏起来。 Then check the value of the selected value in property type and display your divs 然后在属性类型中检查所选值的值并显示div
var s2 = $("#property-types-ids").select2({ placeholder: "Choose property type", tags: true }); var vals = []; vals.forEach(function(e){ if(!s2.find('option:contains(' + e + ')').length) s2.append($('<option>').text(e)); }); s2.val(vals).trigger("change"); $('#for_sales_fields').hide(); $('#for_rents_fields').hide(); $('#property-types-ids').change(function() { $('#for_sales_fields').hide(); $('#for_rents_fields').hide(); var test = []; $.each($('#property-types-ids :selected'), function(){ test.push($(this).val()); if($(this).val() == 1) { $('#for_sales_fields').show(); } if($(this).val() == 2) { $('#for_rents_fields').show(); } }) } );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script> <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.css" rel="stylesheet"/> <select multiple name="event_type[]" class="form-control" id="property-types-ids"> <option value="1">For Sale</option> <option value="2">For Rent</option> </select> <div id ="for_sales_fields"> #sales fields div </div> <div id ="for_rents_fields"> #Rent fields div </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.