简单的if / else点击功能

时间:2017-04-10 04:10:46

标签: javascript jquery if-statement

我正在尝试将if语句添加到下面的函数中。

else语句将包含以下代码,这样color_update不仅会被隐藏,而且会在未单击按钮时被禁用。

$("#color_update").prop('disabled', true);

这是代码功能:

JS

function open(elem) {
    if (document.createEvent) {
        var e = document.createEvent("MouseEvents");
        e.initMouseEvent("mousedown", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
        elem[0].dispatchEvent(e);
    } else if (element.fireEvent) {
        elem[0].fireEvent("onmousedown");
    }
}

$(document).ready(function(){

    $('#update').click(function(event){
        event.preventDefault();
        event.stopImmediatePropagation();
        $('#color_update').addClass("show").focus();
        open( $('#color_update') ); 
        $("#color").prop('disabled', true);

    });

CSS

#color_update {
display: none;
}

HTML

<select id="color">
      <option value="Red">Red</option>
      <option value="Green">Green</option>
      <option value="Blue">Blue</option>
    </select>

    <input type="button" id="update" value="Update" />

    <select id="color_update">
      <option value="Red">Black</option>
      <option value="Green">Purple</option>
      <option value="Blue">White</option>
    </select>

请指导我。谢谢。

1 个答案:

答案 0 :(得分:1)

根据我的理解,您希望在单击按钮时禁用/可以选择两个选择元素中的一个。 以下是同一

fiddle

基本上我们可以使用任一select元素的disabled属性作为决定因素

    $("#color_update").prop('disabled', true); // Disable the select box initially
    $("#color_update").hide(); // Also hide it

    $('#update').click(function() {
      if ($('#color_update').prop('disabled') == true) { // We check the 'disabled' property to determine our next step

        // The button is now disabled, we need to enable it and hide the #color select 
        $("#color_update").prop('disabled', false);
        $("#color").prop('disabled', true);

        // We can now show and hide the respective select elements
        $("#color_update").show();
        $("#color").hide();
      } else { // We can now handle the other case
        $("#color_update").prop('disabled', true);
        $("#color").prop('disabled', false);

        $("#color_update").hide();
        $("#color").show();
      }
    });

如果您需要别的东西,请告诉我

编辑:更新了jsFiddle链接

相关问题