综合编程

JavaScript – Hide buttons according to selected options

微信扫一扫,分享到朋友圈

JavaScript – Hide buttons according to selected options
0

I have two (or in some places more) dropdowns (select) with several options. There is also a button for clearing all selected values in dropdowns. There is one aspect of this clearing button that does not working properly for my needs.

The button is displayed only if dropdowns has selected option with value, after is selected options with empty value, button is hidden. After i choose some option in both dropdowns (button displayed) and then change value in one from this dropdowns to option without value (button is hidden). Problem is, that button is hidden after one from dropdowns has empty value.

I need that button to be hidden only if all dropdowns have a selected option with an empty value. This jsfiddle
illustrates what I mean.

I use select2.js
for the dropdowns.

HTML:

<input type="button" class="opt-clear" value="Clear all dropdowns">
<div class="option">
    <select>
        <option value="">Please select</option>
        <option value="1">Option 1</option>
        <option value="2">Option 2</option>
    </select>
</div>
<div class="option">
    <select>
        <option value="">Please select</option>
        <option value="1">Option 1</option>
        <option value="2">Option 2</option>
    </select>
</div>

Javascript:

$('select').select2();

$('.option select').change(function() {
var id=$(this).val();
if (id=="") {
    $(".opt-clear").hide();
} else {
    $(".opt-clear").show();
}
}).trigger('change');

$(".opt-clear").click(function() { $(".option select").select2("val", ""); });

You have to check the val
from all lists. If at least one them has a value then dont hide the button. You have to use each()
and a var as a flag.

Try:

$('.option select').change(function () {
    var flag = 1;
    $(".option select").each(function (index) {
        var id = $(this).val();
        if (id != "") {
            flag = 0;
        }
    });

    if (flag) {
        $(".opt-clear").hide();
    } else {
        $(".opt-clear").show();
    }
}).trigger('change');

DEMO

阅读原文...


Hello, buddy!

Return ArrayList and use it in another method problem

上一篇

Gmail gets a useful right-click menu

下一篇

您也可能喜欢

评论已经被关闭。

插入图片
JavaScript – Hide buttons according to selected options

长按储存图像,分享给朋友