简体   繁体   中英

Checkbox enable/disable and check/uncheck and also button text change with a single button click

I have a button and the button can have two labels - Activate and Deactivate. If I click on the button, then the button labels interchange, ie if I click on the button and the current text is Activate, then the text is switched to Deactivate and vice versa. I want to do two more things at a time on this button click -

  1. I have a checkbox named IsMandatory. When I click on the button, if it changes from Activate to Deactivate, then the IsMandatory checkbox becomes disabled and vice versa.

  2. Simultaneously, if the Ismandatory checkbox becomes disabled, it will be unchecked. If the checkbox becomes enabled, it becomes checked.

How can I achieve this???

So far I have done this:

<input type="hidden" id="stat" data-bind="value:IsActive" />
<input type="button" id="butt" onclick="change();" />

<input type="hidden" id="stat2" data-bind="value: IsMandatory" />
<input type="checkbox" id="chckbox" data-bind="checked: IsMandatory" />

<script type="text/javascript">

$(function () {


    var stat = document.getElementById("stat").value;
    var stat2 = document.getElementById("stat2").value;
    //alert(stat);

    if (stat == 1) {

        document.getElementById("butt").value = "Activate";
        document.getElementById("chckbox").disabled = false;
        document.getElementById("chckbox").checked = true;
        stat2 = 1;

    }
    else {
        document.getElementById("butt").value = "Deactivate";
        document.getElementById("chckbox").disabled = true;
        document.getElementById("chckbox").checked = false;
        stat2 = 0;

    }

    //if (stat2 == 1)
    //{

    //    document.getElementById("chckbox").checked = false;
    //}
    //else
    //{

    //   document.getElementById("chckbox").disabled = true;
    //}


});


function activeStatus(IsActive) {

    //alert(ActiveStatus);
    if (IsActive == 1) {
        //document.getElementById("chckbox").disabled = false;
        return "Activate";
    }
    else {
        //document.getElementById("chckbox").disabled = true;
        return "Deactivate";
    }
}

function change() {

    var butt = document.getElementById("butt").value;

    if (butt == 'Deactivate') {
        document.getElementById("butt").value = "Activate";
        document.getElementById("chckbox").disabled = false;
        document.getElementById("chckbox").checked = true;
        document.getElementById("stat").value = 1;
        document.getElementById("stat2").value = 1;


    }

    else {
        document.getElementById("butt").value = "Deactivate";
        document.getElementById("chckbox").disabled = true;
        document.getElementById("chckbox").checked = false;
        document.getElementById("stat").value = 0;
        document.getElementById("stat2").value = 0;



    }




}


</script>

EDIT-1: Additional JavaScript Code:

var urlInputConfiguration = "/InputConfiguration";

var url = window.location.pathname;
var Id = url.substring(url.lastIndexOf('/') + 1);


$(function () {

$.ajaxSetup({
    // Disable caching of AJAX responses
    cache: false
});



var InputConfiguration = function (InputConfiguration) {
    var self = this;
    self.Id = ko.observable(InputConfiguration ? InputConfiguration.Id : 0).extend({ required: true });
    self.SectionName = ko.observable(InputConfiguration ? InputConfiguration.SectionName : '');
    self.SectionText = ko.observable(InputConfiguration ? InputConfiguration.SectionText : '');
    self.IsActive = ko.observable(InputConfiguration ? InputConfiguration.IsActive : 1);
    self.IsMandatory = ko.observable(InputConfiguration ? InputConfiguration.IsMandatory : 1);



};

var InputConfigurationCollection = function () {
    var self = this;

    //if ProfileId is 0, It means Create new Profile
    if (Id == 0) {
        self.InputConfiguration = ko.observable(new InputConfiguration());
    }
    else {
        $.ajax({
            url: urlInputConfiguration + '/GetInputConfigurationById/' + Id,
            async: false,
            dataType: 'json',
            success: function (json) {
                self.InputConfiguration = ko.observable(new InputConfiguration(json));
            }
        });
    }

    self.InputConfigurationErrors = ko.validation.group(self.InputConfiguration());





    self.saveInputConfiguration = function () {

        //self.Country = ko.observable(new Country());

        var isValid = true;

        if (self.InputConfigurationErrors().length != 0) {
            self.InputConfigurationErrors.showAllMessages();
            isValid = false;
        }

        // alert(JSON.stringify(ko.toJS(self.Country())));





        if (isValid) {

            //self.InputConfiguration().IsMandatory = document.getElementById("stat2").value;
            self.InputConfiguration().IsActive = document.getElementById("stat").value;


            var activevalue = self.InputConfiguration().IsActive;

            if (activevalue == 1)
            {
                document.getElementById("chckbox").disabled = false;
                //document.getElementById("chckbox").checked = true;
                self.InputConfiguration().IsMandatory = document.getElementById("stat2").value;



            }

            else
            {
                document.getElementById("chckbox").disabled = true;
                //document.getElementById("chckbox").checked = false;
                self.InputConfiguration().IsMandatory = document.getElementById("stat2").value;



            }

            $.ajax({
                type: (Id > 0 ? 'PUT' : 'POST'),
                cache: false,
                dataType: 'json',
                url: urlInputConfiguration + (Id > 0 ? '/UpdateInputConfigurationInformation?id=' + Id : '/SaveInputConfigurationInformation'),
                data: JSON.stringify(ko.toJS(self.InputConfiguration())),
                contentType: 'application/json; charset=utf-8',
                async: false,
                success: function (data) {
                    alert("Case Input Configuration saved successfully.");
                    window.location.href = '/InputConfiguration';
                },
                error: function (err) {
                    var err = JSON.parse(err.responseText);
                    var errors = "";
                    for (var key in err) {
                        if (err.hasOwnProperty(key)) {
                            errors += key.replace("InputConfiguration.", "") + " : " + err[key];
                        }
                    }
                    $("<div></div>").html(errors).dialog({ modal: true, title: JSON.parse(err.responseText).Message, buttons: { "Ok": function () { $(this).dialog("close"); } } }).show();
                },
                complete: function () {
                }
            });
        }
    };
};


var InputConfigurationsViewModel = function () {
    var self = this;
    var url = "/InputConfiguration/GetAllInputConfiguration";
    var refresh = function () {
        $.getJSON(url, {}, function (data) {
            self.InputConfigurations(data);
        });
    };

    // Public data properties
    self.InputConfigurations = ko.observableArray([]);

    // Public operations
    self.createInputConfiguration = function () {
        window.location.href = '/InputConfiguration/InputConfigurationCreateEdit/0';
    };

    self.editInputConfiguration = function (inputConfiguration) {
        //alert(country.CountryID);
        window.location.href = '/InputConfiguration/InputConfigurationCreateEdit/' + inputConfiguration.Id;
    };
    self.removeInputConfiguration = function (inputConfiguration) {

        // First remove from the server, then from the UI
        if (confirm("Are you sure you want to delete this profile?")) {

            var id = customerProfileConfiguration.Id;
            $.ajax({ type: "DELETE", url: 'InputConfiguration/DeleteInputConfiguration/' + id })
                .done(function () { self.CustomerProfileConfigurations.remove(inputConfiguration); });
        }
    }
    refresh();




};

ko.applyBindings(new InputConfigurationsViewModel(), document.getElementById("inputconfigurationlist"));
ko.applyBindings(new InputConfigurationCollection(), document.getElementById("inputconfiguration_edit"));
});

var clone = (function () {
    return function (obj) {
        Clone.prototype = obj;
        return new Clone()
    };
function Clone() { }
}());

I can't bind the value of IsMandatory, although check/uncheck along with enable/disable is working fine when I click the button. Also, while my button text is Activate, IsActive value is bound as 1, and when my button text is Deactivate, IsActive value is bound as 0. When checkbox is checked, IsMandatory value should have been 1, when checkbox is unchecked, IsMAndatory value should have been 0.

Binding had to be used by force, I tried to use knockout but that's not actually helping.

So first of all, when I get the button value, without clicking it, by using document.getElementById and keeping it inside a variable stat, I had to make sure that if stat = 1, then another variable stat2 which has the value from the checkbox becomes 1 as well. Next, when stat2 = 1, checkbox will be checked. Similar thing was done in the else statement when stat = 0. So now stat2 = 0, and checkbox is unchecked.

if (stat == 1)
{

    document.getElementById("butt").value = "Activate";
    document.getElementById("chckbox").disabled = false;
    stat2 = 1;
    if (stat2 == 1) {

        document.getElementById("chckbox").checked = true;
    }
    else {

        document.getElementById("chckbox").disabled = false;
    }

}
else
{
    document.getElementById("butt").value = "Deactivate";
    document.getElementById("chckbox").disabled = true;
    stat2 = 0;

    if (stat2 == 0) {

        document.getElementById("chckbox").checked = false;
    }
        else {

            document.getElementById("chckbox").disabled = true;
        }

 }

Next, the change is incorporated inside the function change(). That means when I click the button, then the change() function is called. Inside it, I had to make sure that if Deactivate becomes Activate, then document.getElementById("stat2").value becomes 1 and if 1, then checkbox should be checked. Reverse would happen if we change from Activate to Deactivate.

function change() {

    var butt = document.getElementById("butt").value;

    if (butt == 'Deactivate')
    {
        document.getElementById("butt").value = "Activate";
        document.getElementById("chckbox").disabled = false;
        document.getElementById("stat").value = 1;
        document.getElementById("stat2").value = 1;

        if ((document.getElementById("stat2").value) == 1)
        {
            document.getElementById("chckbox").checked = true;
        }

        else
        {
            document.getElementById("chckbox").checked = false;
        }



    }

    else
    {
        document.getElementById("butt").value = "Deactivate";
        document.getElementById("chckbox").disabled = true;
        document.getElementById("chckbox").checked = false;
        document.getElementById("stat").value = 0;
        document.getElementById("stat2").value = 0;

        if ((document.getElementById("stat2").value) == 0)
        {
            document.getElementById("chckbox").checked = false;
        }

        else
        {
            document.getElementById("chckbox").checked = true;
        }


    }

}

Finally, I'm force binding this value of the checkbox inside my IsMandatory property, which is inside my js file. IsMandatory property is the property that I declared in the view model for checkbox. IsActive is the property for button. Whenever IsActive is 1, then I enable the checkbox and then I take the value from my checkbox by using document.getElementById. If value of checkbox = 1, then IsMandatory becomes 1, else IsMandatory becomes 0.

self.InputConfiguration().IsActive = document.getElementById("stat").value;
self.InputConfiguration().IsMandatory = document.getElementById("stat2").value;


var activevalue = self.InputConfiguration().IsActive;
var check = self.InputConfiguration().IsMandatory;


if (activevalue == 1)
{
    document.getElementById("chckbox").disabled = false;
    //document.getElementById("chckbox").checked = true;


    check = 1;
    if (check == 1) {
        self.InputConfiguration().IsMandatory = 1;
    }

    else
    {
        self.InputConfiguration().IsMandatory = 0;
    }
}

else
{
    document.getElementById("chckbox").disabled = true;
    check = 0;
    //document.getElementById("chckbox").checked = false;

    if (check == 0) {
        self.InputConfiguration().IsMandatory = 0;
    }

    else
    {
        self.InputConfiguration().IsMandatory = 1;
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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