We use cookies to give you the best experience on our website. If you continue to browse, then you agree to our privacy policy and cookie policy. Image for the cookie policy date

Option Group across rows in grid - Allow only one row to have a checkbox selected in grid

I have a grid showing a list of names and want the user to be able to select a preferred name from the last.  This is a checkbox available in each row.

When I user selects a name as preferred name, need to be able to check if it has been ticked for other names. and if it is, update the row that is currently ticked as preferred name and the row that is now the preferred name.

It would be very useful if there is an example.

Thanks,
Steve

8 Replies

PK Prasanna Kumar Viswanathan Syncfusion Team March 14, 2017 12:15 PM UTC

Hi Steve,  

Thanks for contacting Syncfusion support. 

According to your requirement, we suspect that you have list of names in one column and checkboxes in another column. When the user select the name you want to check the checkbox for the corresponding row and previously if any other checkbox is checked then you want to uncheck the checkbox for the corresponding row.  

We have created a sample for your requirement and in this sample we used columnTemplate feature and rowSelecting event of ejGrid.  In columnTemplate HTML templates can be specified in the template property of the particular column as a string (HTML element) and using templateRefresh event of ejGrid we have render the ejCheckbox in the template column.  

The rowSelecting event will be triggered before the row is going to be selected. In this event we can get the target in the arguments and using that we checked/unchecked the checkboxes. We checked/unchecked the checkboxes using checked API of ejCheckBox.  

Find the code example and sample:  


@(Html.EJ().Grid<object>("FlatGrid") 
   .Datasource((IEnumerable<object>)ViewBag.datasource) 
   .AllowSorting() 
   .AllowPaging() 
   .ClientSideEvents(eve => { eve.TemplateRefresh("refresh").RowSelecting("rowselect"); }) 
   .SelectedRowIndex(3) 
   .Columns(col => 
   { 
      col.HeaderText("Employee Image").Template("<input type='checkbox' id='{{:EmployeeID}}'/>").TextAlign(TextAlign.Center).Width(80).Add(); 
      col.Field("FirstName").HeaderText("First Name").Width(80).Add(); 
    }) 
) 
   
<script type="text/javascript"> 
    function refresh(args) { 
        $(args.cell).find("input").ejCheckBox(); 
    } 
 
    function rowselect(args) { 
        if (ej.isNullOrUndefined(args.target)) { 
            $($(args.row).find("input")[0]).ejCheckBox({ checked: true }); 
        } 
        else if (args.target.hasClass("e-rowcell") && !args.target.hasClass("e-templatecell")) { 
            $($(this.getSelectedRows()[0]).find("input")[0]).ejCheckBox({ checked: false }); 
            $($(args.row).find("input")[0]).ejCheckBox({ checked: true }); 
        } 
        else { 
            args.cancel = true; 
        } 
    } 
</script> 


Refer to the Help documents.  





If we misunderstood your requirement, please elaborate the requirement it will help us to provide the better solution.  

Regards, 
Prasanna Kumar N.S.V 
 



SA Stephen Armstrong March 15, 2017 01:34 AM UTC

Hi Prasanna,

Thank-you for getting back to me.

Unfortunately this is not quite what I am looking for.  I need to put an event on the actual checkbox when it is checked/unchecked, not on rowselect. 

My grid is a list of names including aliases and has columns which include first name, last name, and preferred name (checkbox).  When a new name is added, or an existing one is edited, I need to be able to go through each row and check if other names in the list are the preferred name (ie. the preferred name checkbox is checked)  If a person already has a preferred name and you want to change the preferred name to the new record, I want to display an alert to confirm, and if the user says yes, the checkbox in the old preferred name row is unchecked and the checked box in the new preferred name is checked.

Does that help?

Steve


FS Farveen Sulthana Thameeztheen Basha Syncfusion Team March 16, 2017 04:59 PM UTC

Hi Steve, 


We have created the sample according to your requirement which can be downloaded from the below location. 

 
 
 
We have achieved your requirement using “actionComplete” and “templateRefresh” events. When we save the modifed or added data “actionComplete” event get triggers. In this event, we have rendered the ejDialog with ok and cancel buttons. When we click “ok” button, on click event of this Button, we have disabled the already checked checkbox and enabled the newly added or modified data to be checked( i.e. as preferred name)by getting the edited row using its window.rowIndex value. When we click “cancel” button, already checked item to be continued as preferred name. 
 
 
 Also  we have maintained the checkbox state on editing in the templateRefreshevent. We have stored the selected row as private variable on the click event of the checkbox and on editing we have persist the checkbox to be in checked state by using its selectedrow value. 


Please refer the API document events:- 

 
 
 
Please refer to the code example:- 

@{Html.EJ().Dialog("dialog") 
        .Title("Dialog") 
        .ShowOnInit(false) 
        .ContentTemplate( @<div><p>Want this as preferred name</p> 
                @Html.EJ().Button("button1").Text("ok").ClientSideEvents(evt => evt.Click("click")) 
                @Html.EJ().Button("button2").Text("Cancel").ClientSideEvents(evt => evt.Click("click1")) 
 
      </div>) 
        .Render(); 
} 
    
 
 
@(Html.EJ().Grid<object>("FlatGrid") 
        .Datasource((IEnumerable<object>)ViewBag.datasource) 
         .EditSettings(edit => edit.AllowEditing().AllowDeleting().AllowAdding()) 
         .ToolbarSettings(toolbar => 
                    { 
                        toolbar.ShowToolbar().ToolbarItems(items => 
                        { 
                            items.AddTool(ToolBarItems.Add); 
                            items.AddTool(ToolBarItems.Edit); 
                            items.AddTool(ToolBarItems.Delete); 
                            items.AddTool(ToolBarItems.Update); 
                            items.AddTool(ToolBarItems.Cancel); 
                        }); 
           }) 
    
     .ClientSideEvents(eve =>eve.TemplateRefresh("refresh").ActionComplete("complete"); 
})     
 
.Columns(col => 
       { 
      col.HeaderText("Employee Image").Template("<input type='checkbox' id='{{:EmployeeID}}'/>").TextAlign(TextAlign.Center).Width(80).Add(); 
           . . .  
    }) 
      
 ) 
   
<script type="text/javascript"> 
    window.rowIndex = -1; 
         window.selectedIndex = -1; 
     function refresh(args) {         // templateRefresh event to persist the checkbox state on editing 
      if (window.selectedIndex == args.rowIndex) { 
        var obj = $(".e-grid").ejGrid("instance") 
        $(obj.getRows()).find("input[type='checkbox']:checked").click(); 
        obj.getRowByIndex(window.selectedIndex).find("input[type='checkbox']").click(); 
      } 
        $(args.cell).find("input").click(function () {  // click event of the checkbox 
            window.selectedIndex = $(".e-grid").ejGrid("getIndexByRow", $(this).closest("tr")) 
        }) 
       } 
        function complete(args) { 
        if (args.requestType== "save"){ 
           $("#dialog").ejDialog("open");   // dialog box opens in the actionComplete event 
       } 
      } 
    function click() {              // ok button click to check the newly added row as preferred name 
        var obj = $(".e-grid").ejGrid("instance") 
        $(obj.getRows()).find("input[type='checkbox']:checked").click(); 
        obj.getRowByIndex(window.rowIndex).find("input[type='checkbox']").click(); 
        $("#dialog").ejDialog("close"); 
    } 
    function click1() { 
       $("#dialog").ejDialog("close");  // cancel button click 
    } 
 
</script>  

 


Regards, 

Farveen sulthana T 



SA Stephen Armstrong March 17, 2017 03:39 AM UTC

Hi Farveen,

I am getting closer but can't seem to get my checkbox 'IsPreferred' to bind to the model.  What am I doing wrong? 

Here is my code.

        @{ Html.EJ().Dialog("dialogPreferredName")
                            .Title("Preferred Name")
                            .ShowOnInit(false)
                            .ContentTemplate(@<div>
                            <p>Are you sure you would like this as your preferred name?</p>
                            @Html.EJ().Button("btnYes").Text("Yes").ClientSideEvents(e => e.Click("onClickYes"))
                            @Html.EJ().Button("btnNo").Text("No").ClientSideEvents(e => e.Click("onClickNo"))
                        </div>).Render();
        }
        @* SynchFusion Grid for Person Names *@
        @(Html.EJ().Grid<PersonNamesViewModel>("PersonNamesGrid")
            .Datasource(ds => ds.Json(Model.personNamesViewModel)
                .Adaptor(AdaptorType.RemoteSaveAdaptor)
                .InsertURL("PerformPersonNameInsert")
                .RemoveURL("PerformPersonNameDelete")
                .UpdateURL("PerformPersonNameUpdate"))
            .EditSettings(edit => { edit.AllowAdding().AllowDeleting().AllowEditing().RowPosition(RowPosition.Bottom).ShowDeleteConfirmDialog(); })
            .ToolbarSettings(toolbar =>
            {
                toolbar.ShowToolbar().ToolbarItems(items =>
                {
                    items.AddTool(ToolBarItems.Add);
                });
            })
            .Columns(col =>
            {
                col.Field(p => p.NameId).IsPrimaryKey(true).IsIdentity(true).Visible(false).Add();
                col.Field(p => p.PersonId).Visible(false).DefaultValue(Model.PersonId).Add();
                col.Field(p => p.LastName).HeaderText(@Html.DisplayNameFor(model => model.personNamesViewModel[0].LastName).ToString()).ValidationRules(v => v.AddRule("required", true)).Add();
                col.Field(p => p.FirstName).HeaderText(@Html.DisplayNameFor(model => model.personNamesViewModel[0].FirstName).ToString()).ValidationRules(v => v.AddRule("required", true)).Add();
                col.Field(p => p.OtherName).HeaderText(@Html.DisplayNameFor(model => model.personNamesViewModel[0].OtherName).ToString()).Add();
                col.HeaderText(@Html.DisplayNameFor(model => model.personNamesViewModel[0].IsPreferred).ToString()).Template("<input type='checkbox' id='{{:IsPreferred}}'/>").Width(150).Add();
                col.Field(p => p.NameCodeId)
                    .HeaderText(@Html.DisplayNameFor(model => model.personNamesViewModel[0].NameCodeId).ToString())
                    .ForeignKeyField("Value")
                    .ForeignKeyValue("Text")
                    .DataSource(Model.NameCodes.ToList())
                    .Width(100).Add();
                col.Field(p => p.BirthDate).HeaderText(@Html.DisplayNameFor(model => model.personNamesViewModel[0].BirthDate).ToString()).EditType(EditingType.Datepicker).Format("{0:dd/MM/yyyy}").Width(100).Add();
                col.Field(p => p.Age).HeaderText(@Html.DisplayNameFor(model => model.personNamesViewModel[0].Age).ToString()).Width(75).Add();
                col.Field(p => p.GenderCodeId)
                    .HeaderText(@Html.DisplayNameFor(model => model.personNamesViewModel[0].GenderCodeDescription).ToString())
                    .ForeignKeyField("Value")
                    .ForeignKeyValue("Text")
                    .DataSource(Model.GenderCodes.ToList())
                    .Width(100).Add();
                col.HeaderText("Actions").Commands(commands =>
                {
                    commands.Type(UnboundType.Edit).ButtonOptions(new ButtonProperties()
                    {
                        ContentType = ContentType.ImageOnly,
                        PrefixIcon = "e-icon e-edit"
                    }).Add();
                    commands.Type(UnboundType.Delete).ButtonOptions(new ButtonProperties()
                    {
                        ContentType = ContentType.ImageOnly,
                        PrefixIcon = "e-icon e-delete"
                    }).Add();
                    commands.Type(UnboundType.Save).ButtonOptions(new ButtonProperties()
                    {
                        ContentType = ContentType.ImageOnly,
                        PrefixIcon = "e-icon e-save"
                    }).Add();
                    commands.Type(UnboundType.Cancel).ButtonOptions(new ButtonProperties()
                    {
                        ContentType = ContentType.ImageOnly,
                        PrefixIcon = "e-icon e-cancel"
                    }).Add();
                }).Width(150).Add();
            })
            .ClientSideEvents(e => { e.Create("onCreate").TemplateRefresh("onTemplateRefresh").ActionComplete("onComplete"); })
        )


SA Stephen Armstrong March 17, 2017 04:58 AM UTC

Hi,

I seem to have it working now, but am not sure how to save the additional row where IsPreferred is changed from true to false.  Any ideas?

Here is my script...
window.rowIndex = -1;

function onComplete(args) {
    var obj = $(".e-grid").ejGrid("instance");
    var isChecked = obj.getRowByIndex(window.rowIndex).find("input[type='checkbox']").prop('checked');
    if (args.requestType == "save" && isChecked) {
        $("#dialogPreferredName").ejDialog("open");   // dialog box opens in the actionComplete event 
    }
}

function onClickYes() {              // ok button click to check the newly added row as preferred name 
    var obj = $(".e-grid").ejGrid("instance");
    $(obj.getRows()).find("input[type='checkbox']:checked").prop('checked', false);
    obj.getRowByIndex(window.rowIndex).find("input[type='checkbox']").prop('checked', true);
    $("#dialogPreferredName").ejDialog("close");
}
function onClickNo() {
    $("#dialogPreferredName").ejDialog("close");  // cancel button click 
}

Thanks,
Steve


AS Alan Sangeeth S Syncfusion Team March 20, 2017 11:17 AM UTC

Hi Stephen, 


We have optimized the sample which we have provided earlier and please find the sample link below. 

In this sample, we have Verified boolean column bind with “Field” property of Grid Column and set its “EditType”  property as Boolean to display checkbox while editing the record. 

Using ActionBegin events, we have displayed Dialog to confirm Preferred name. Please refer the following code example. 
@(Html.EJ().Grid<object>("FlatGrid") 
      
          
   .Columns(col => 
   { 
      col.Field("Verified").EditType(EditingType.Boolean).TextAlign(TextAlign.Center).Width(80).Add(); 
 
    }) 
     .ClientSideEvents(eve => { eve.ActionBegin("begin").ActionComplete("complete"); }) 
 ) 
   
<script type="text/javascript"> 
    window.preferredData = null; 
    window.currentData = null; 
    function begin(args) { 
        if (args.requestType == "save") { 
            if (args.data.Verified) { 
                var data = ej.DataManager(this.model.dataSource).executeLocal(new ej.Query().where("Verified", "equal", true, false)) 
                if (data.length && data.EmployeeID != args.data.EmployeeID) { 
                    preferredData = data[0]; 
                    currentData = args.data; 
                    args.cancel = true; 
                    $("#dialog").ejDialog("open"); 
                } 
            } 
        } 
    } 
 
    function click() { 
        var obj = $(".e-grid").ejGrid("instance"); 
        window.preferredData.Verified = false; 
        var isAdd = obj.getContent().find(".e-addedrow").length; 
        obj.cancelEdit(); 
        obj.updateRecord("EmployeeID", window.preferredData); 
        if (!isAdd) 
            obj.updateRecord("EmployeeID", window.currentData); 
        else 
            obj.addRecord(window.currentData); 
        $("#dialog").ejDialog("close"); 
    } 
    function click1() { 
       $("#dialog").ejDialog("close"); 
    } 
 
</script> 

In your last update, you have mentioned that you want to show add row form when there is no preferred name selected in Grid. We have achieved this requirement using “ActionComplete” Grid event. Please refer the following code example/ 
function complete(args) { 
        if (args.requestType == "save") { // If no Preferred name selected, show add form using addRecord method 
            var data = ej.DataManager(this.model.dataSource).executeLocal(new ej.Query().where("Verified", "equal", true, true)) 
            if (!data.length) 
                this.addRecord(); 
        } 
    } 

If we misunderstood your requirement, please get back to us with more clear details so that we could provide you response as early as possible. 

Regards,
Alan Sangeeth S 



SA Stephen Armstrong March 21, 2017 01:34 AM UTC

Hi Alan,

This looks good and I have it working when I edit a record.

However, when I add a new record and select that record as preferred, the obj.cancelEdit(); line cancels the add new and the code finishes

function onClickYes() {              // ok button click to check the newly added row as preferred name 
    var obj = $(".e-grid").ejGrid("instance");
    window.preferredData.IsPreferred = false;
    var isAdd = obj.getContent().find("e-addedrow").length;
    obj.cancelEdit();
    obj.updateRecord("NameId", window.preferredData);
    if (!isAdd)
        obj.updateRecord("NameId", window.currentData);
    else
        obj.addRecord(window.currentData);

    $("#dialogPreferredName").ejDialog("close");
}

Any ideas?

Thanks for all your help.
Steve


FS Farveen Sulthana Thameeztheen Basha Syncfusion Team March 22, 2017 11:06 AM UTC

Hi Steve, 


We are unable to reproduced your reported problem “when I add a new record and select that record as preferred, the obj.cancelEdit(); line cancels the add new” at our end. Could you please share us the following details to find the cause of the issue. 


1. Have you used code example provided by us in your application. If yes, please share us the modified Grid code example. 


2. Screenshot/Video regarding that issue.  


3. Replication procedure of the issue. 


4. If possible, replicate the issue in the above sample and send us back. 


The provided details will helps us to analyze and provide you solution as early as possible.  


Please check the video of the sample that the issue was not reproduced. 



Regards, 

Farveen sulthana T 


Loader.
Live Chat Icon For mobile
Up arrow icon