Iman Yasmin
Iman Yasmin

Reputation: 447

Simple if/else click function

I'm trying to add if else statement to below function.

The else statement will contain the following code so that color_update not only will be hidden but at the same time disabled when the button is not clicked.

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

This is the code function:

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>

Please guide me. Thank you.

Upvotes: 0

Views: 1310

Answers (1)

Mayank Raj
Mayank Raj

Reputation: 1624

From what I could understand, you want to disable/enbable one of the two select elements on the click of the button. Here is the fiddle for the same

Essentially we can use the disabled property of either of the select element as the deciding factor

    $("#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();
      }
    });

Do let me know if you need something else

EDIT: Updated the jsFiddle link

Upvotes: 1

Related Questions