jqueryajaxasp.net-mvcasp.net-mvc-5toggleswitch

CheckBox To Behave Like Toggle Switches


I've an ASP.NET application where it has a list of products in a page with related details and with status column (Bit field - CheckBox). It works perfectly and I can change the status from true to false or vice-versa using Ajax. While doing so, I am keeping the state of the CheckBox means if it's true, then it remains checked, otherwise unchecked. See the image below except the red highlighted (One more thing - True means active and false means inactive product in this scenario):

Sample Image

Now what I am trying is to make the CheckBoxes into toggle switch as well to keep the changes of the CheckBoxes something like this - BootStrap Toggle Switches

I am not sure how to do it and tried to follow this to make the CheckBoxes work as the toggle switch using class as follows - jQuery Toggle Switches

<script>
    $(document).ready(function () {
        $('.toggle-checkbox').btnSwitch({
            Theme: 'Light',

            OnText: "On",
            OffText: "Off",

            OnValue: true,
            OffValue: false
        });
    });
</script>

Note: I've to keep the states of the CheckBoxes shown in the image that aren't red highlighted like for true, checked and vice-versa. Would be delighted to know if this is possible to do the same with toggle switches.

Database Script:

CREATE TABLE [dbo].[Products](
  [Id] [int] IDENTITY(1,1) PRIMARY KEY,
  [ProductName] [nvarchar](MAX) NOT NULL,
  [Time_Posted] [nvarchar](MAX) NOT NULL,
  [Status] [bit] NOT NULL
)

INSERT INTO Products VALUES
('Denim', '7:30:10 PM', 1),
('Pringles', '8:00:00 PM', 1)

Model:

public class Product
{
    public int Id { get; set; }
    public string ProductName{ get; set; }
    public string Time_Posted { get; set; }
    public bool Status { get; set; }
}

Controller:

//Get details of the products
[HttpGet]
public ActionResult Index()
{
    MainDbContext db = new MainDbContext();

    var con = (from c in db.Products
               select c).ToList();

    return View(con);
}

//Update status of the products like active or inactive    
[HttpPost]
public JsonResult UpdateStatus(int id, bool status)
{
     MainDbContext db = new MainDbContext();
     var result = db.Lists.Find(id);

     if (result != null)
     {
        result.Status = status;
        db.Entry(result).State = EntityState.Modified;
        db.SaveChanges();
     }
     return Json(true);
 }

View:

@model SampleApp.Models.Product
@{
    ViewBag.Title = "Index";
}

<link href="~/Scripts/jquery.btnswitch.css" rel="stylesheet" />
<script src="~/Scripts/jquery-3.1.1.slim.min.js"></script>
<script src="~/Scripts/jquery.btnswitch.js"></script>

<div id="divData">
    <table class="table table-bordered table-condensed" id="data">
        <thead>
            <tr>
                <th style="text-align:center;" class="hide">ID</th>
                <th style="text-align:center;">Products</th>
                <th style="text-align:center;">Time Posted</th>
                <th style="text-align:center;">Status</th>
            </tr>
        </thead>
        <tbody>
        @for (int i = 0; i < Model.Items.Count; i++)
        {
           <tr>
               <td id="ID" style="text-align: center;" class="hide">@Html.DisplayFor(modelItem => Model.Items[i].Id)</td>
               <td style="text-align: center;">@Html.DisplayFor(modelItem => Model.Items[i].ProductName)</td>
               <td style="text-align: center;">@Html.DisplayFor(modelItem => Model.Items[i].Time_Posted)</td>
               <td style="text-align: center;">@Html.CheckBoxFor(modelItem => Model.Items[i].Status, new { @class = "toggle-checkbox", data_id = Model.Items[i].Id })</td>        
           </tr>
        }
        </tbody>
    </table>
</div>

<script type="text/javascript">
    var url = '@Url.Action("UpdateStatus")';
    $('.toggle-checkbox').click(function () {

        var isChecked = $(this).is(':checked'); //CheckBox checked - True or false
        var id = $(this).data('id'); //Get the id of that specific checked row

        $.post(url, { id: id, status: isChecked }, function (response) {
            if (response) {
                alert("Status changed");
            } 
        })
    });
</script>

<script>
    $(document).ready(function () {
        $('.toggle-checkbox').btnSwitch({ //This is the script for toggling
            Theme: 'Light', 

            OnText: "On",
            OffText: "Off",

            OnValue: true,
            OffValue: false
        });
    });
</script>

Solution

  • you can using event in jQuery Toggle Switches

    $('.toggle-checkbox').btnSwitch({
       OnValue: 'On',
       OnCallback: function(val) {
           //your ajax code here
       },
       OffValue: 'Off',
       OffCallback: function (val) {
         //your ajax code here
       }
      });
    

    for changing toggle using this code:

    $('#toggle-checkbox').btnSwitch({
       ToggleState:true  //for switch on / true
      });
    
    $('#toggle-checkbox').btnSwitch({
       ToggleState:false  //for switch off / false
      });