This is a migrated thread and some comments may be shown as answers.

[Solved] Mandatory value in combobox?

19 Answers 342 Views
ComboBox
This is a migrated thread and some comments may be shown as answers.
This question is locked. New answers and comments are not allowed.
Julien
Top achievements
Rank 1
Julien asked on 09 Feb 2012, 09:29 AM
Hi, 

I'm using the combobox(in combobox mode) http://demos.telerik.com/aspnet-mvc/combobox  to display list of items.

I love the ways it suggest me directly multiple element(auto-complete style), with the possibility to chose one element in the dropdownlist.

But is there a way to have this behavior:
-If it wrote something that doesn't have any match(and exit the field), the combobox takes the last valid choosen value? I want that it's mandatory to choose an element in the list AND have the combobox proposition(e.g. if I've already written "co", I can get proposition like "Company", "Coffee", ...

Thank you

19 Answers, 1 is accepted

Sort by
0
Georgi Krustev
Telerik team
answered on 09 Feb 2012, 11:59 AM
Hello Julien,

 
In order to acheive your goal you will need to wire the OnChange event and set the required value when user enters incorrect (not allowed) value:

function onChange() {
   var combobox = $(this).data("tComboBox");
   if (combobox.value() && combobox.selectedIndex == -1) {
      //custom value is entered.
      // set the required value here.
   }
}

Regards,
Georgi Krustev
the Telerik team
Sharpen your .NET Ninja skills! Attend Q1 webinar week and get a chance to win a license! Book your seat now >>
0
Julien
Top achievements
Rank 1
answered on 09 Feb 2012, 12:40 PM
His there a new/old value in the event of onChange? How do I retrieve the previous element?

When exactly the "onChange" event is triggered? When we lost focus?
0
Georgi Krustev
Telerik team
answered on 10 Feb 2012, 04:24 PM
Hello Julien,

You can get the previous value of the combobox like this:
function onChange() {
   var combobox = $(this).data("tComboBox");
   var oldValue = combobox.previousValue;
}

The change event will be raised when the input loses focus or on item click.
 
Regards,
Georgi Krustev
the Telerik team
Sharpen your .NET Ninja skills! Attend Q1 webinar week and get a chance to win a license! Book your seat now >>
0
Julien
Top achievements
Rank 1
answered on 21 Feb 2012, 01:10 PM
I did this:

function onComboboxMandatoryValidValue() {
    var combobox = $(this).data("tComboBox");
    if ( combobox.selectedIndex == -1) {
        var index = -1;
        for (var i = 0; i < combobox.data.length; i++) {
            if (combobox.data[i].Value == combobox.previousValue) {
                index = i;
                break;
            }
        }
        combobox.select(index);
    }
}


But it doesn't works for the first value because it didn't find any previous value(and this is normal because nothing is selected by default.

To remove what has been written, what should I do? set the text to "" through Jquery?


EDIT: I found it on the doc :), it wasn't in demo:
http://www.telerik.com/help/aspnet-mvc/telerik-ui-components-combobox-client-api-and-events.html#text 

function onComboboxMandatoryValidValue() {
    var combobox = $(this).data("tComboBox");
    if ( combobox.selectedIndex == -1) {
        var index = -1;
        for (var i = 0; i < combobox.data.length; i++) {
            if (combobox.data[i].Value == combobox.previousValue) {
                index = i;
                break;
            }
        }
        if (index != -1) {
            combobox.select(index);
        } else {
            combobox.text('');
        }
    }
}

But I'm not fully satisfied of the manner that I get the index of the value I get. Is there a better way to do it?
0
Georgi Krustev
Telerik team
answered on 22 Feb 2012, 06:41 PM
Hello,

 
One possible solution is to this:

function onComboboxMandatoryValidValue() {
    var combobox = $(this).data("tComboBox");
 
    if ( combobox.selectedIndex == -1) {
        combobox.value(combobox.previousValue);
 
        if (combobox.selectedIndex) {
             combobox.value("");
        }
    }
}
Greetings,
Georgi Krustev
the Telerik team
If you want to get updates on new releases, tips and tricks and sneak peeks at our product labs directly from the developers working on the Telerik Extensions for ASP.MET MVC, subscribe to their blog feed now.
0
Julien
Top achievements
Rank 1
answered on 23 Feb 2012, 08:45 AM
works great now :) Thanks
0
Julien
Top achievements
Rank 1
answered on 07 Mar 2012, 02:15 PM
In fact I've one last problem:

If in my list I've some language:

French
English
German


And I start typing "FRE". French is now selected(and the end of the word is completed because I've the AutoFill set to true. 

If I'm satisfied with this option, I would like to the next input and I hit the "Tab" key. Then I go to the next input, but it has reverted my choice.

I checked, it seems that the combobox.SelectedIndex return -1.

How can I avoid this?
0
Georgi Krustev
Telerik team
answered on 11 Mar 2012, 08:34 PM
Hello Julien,

 
The combobox will select an item only if the typed text matches exactly the item's text (the casing is important too).  You can force an item selection on change event:

function onComboBoxChange(e) {
   var combobox = $(this).data("tComboBox");
 
   var item = combobox.dropDown.$items.filter(".t-state-selected");
   combobox.select(item);
}
Greetings,
Georgi Krustev
the Telerik team
If you want to get updates on new releases, tips and tricks and sneak peeks at our product labs directly from the developers working on the Telerik Extensions for ASP.MET MVC, subscribe to their blog feed now.
0
Phil
Top achievements
Rank 1
answered on 19 May 2012, 01:48 PM
Hi,

I think i have a cleaner way if anyone is interested.

Hook up the OnLoad event to call onComboBoxLoadEnforce function.
@(Html.Telerik().ComboBox()
           .Name("ComboBox")                                   
           .ClientEvents(events => events.OnLoad("onComboBoxLoadEnforce"))
           ...

Here's the onComboBoxLoadEnforce function.
It hooks up a blur event to the underlying textbox of the combobox control.
The blur event handler checks that the typed text is a valid list item by looking at the combobox's selected index. 
If it isn't, then it's not legal and it clears the text box.
If you combine this with a [required] validator (not shown) it's great for form entries whereby an item must be chosen from the list.
(I'm using ajax to retrieve my list data so i do a rebind too to refresh the list, but only if something was typed)
// Hooks up visible textbox's blur event
// to enforce typed input is on list
// else it clears textbox and reloads list if relevant
function onComboBoxLoadEnforce(e) {
    var combobox = $(this).data('tComboBox');
    $(this).closest(".t-combobox")
           .find("input:visible")
           .bind({
               blur: function (e) {
                   if (combobox.selectedIndex == -1) {
                       if (combobox.text() != "") {
                           combobox.value("");
                           combobox.text("");
                           combobox.reload();
                       }
                       else {
                           combobox.value("");
                       }
                   }
               }
           });

Hope this helps someone.

Phil
0
João
Top achievements
Rank 1
answered on 31 May 2012, 02:00 PM
Thanks for the tip Phil. I used your solution, however without the call to reload, which was causing a js error. I took it out and the ComboBox still reloads the items when the text is changed.
0
Phil
Top achievements
Rank 1
answered on 31 May 2012, 02:21 PM
Hi Joao,

Ive amended it a bit to cover the scenario of focus shifting from the text box of the combo to the dropdown part. In this case you don't want to clear illegal entries until the combo dropdown closes. Therefore i use two function like so:

Here's how i hook up 2 events on the grid
  

  .ClientEvents(events => events.OnLoad("ComboBox_OnLoadEnforce")

  .OnClose("ComboBox_OnCloseEnforce")

 

 

And here's the javascript i've added to my javascript library
   

 

// -- ComboBox Functions -----

 

// Hooks up visible textbox's blur event

// to enforce typed input is on list

// else it clears textbox and reloads list if relevant

function ComboBox_OnLoadEnforce(e)

{

    var combobox = $(this).data('tComboBox');

    combobox.fill();

    $(this).closest(".t-combobox")

           .find("input:visible")

           .bind({

               blur: function (e) {

                   if (combobox.selectedIndex == -1)

                   {

                        // focus could shift to scrollbar of dropdown in which case we should

                        // not clear contents

                       var focusId = $("*:focus").attr("id");

                       if (typeof focusId != 'undefined')

                       {

                           if (combobox.text() != "")

                           {

                               combobox.value("");

                               combobox.text("");

                               if (typeof combobox.selectedValue != 'undefined') {

                                   combobox.selectedValue = "";

                               }

                               combobox.reload();

                           }

                           else

                           {

                               combobox.value("");

                               if (typeof combobox.selectedValue != 'undefined') {

                                   combobox.selectedValue = "";

                               }

                           }

                       }

                   }

               }

           });

}

 

function ComboBox_OnCloseEnforce(e)

{

    var combobox = $(this).data('tComboBox');

    combobox.fill();

    if (combobox.selectedIndex == -1)

    {

        if (combobox.text() != "")

        {

            combobox.value("");

            combobox.text("");

            if (typeof combobox.selectedValue != 'undefined') {

                combobox.selectedValue = "";

            }

            combobox.reload();

        }

        else

        {

            combobox.value("");

            if (typeof combobox.selectedValue != 'undefined') {

                combobox.selectedValue = "";

            }

        }

    }

}

 

 

Hope this helps.
Phil

 

 

 

 

 

 

 

 

0
Abhiram
Top achievements
Rank 2
answered on 19 Jun 2012, 12:50 PM
Using filteredDataIndexes property we can check it



 if ($("#cmbTest").data("tComboBox").selectedIndex == -1) 
      {
           if ($("#cmbTest").data("tComboBox").filteredDataIndexes.length == 0) 
                  {
                         Error = Error + '<li>' + "The Currency is invalid." + '</li>\n'
                     }
       }
0
Abhiram
Top achievements
Rank 2
answered on 19 Jun 2012, 01:15 PM
If u press tab for next selection,just add the inner condition.

if ($("#cmbTest").data("tComboBox").selectedIndex == -1) 
      {
           if ($("#cmbTest").data("tComboBox").filteredDataIndexes.length == 0) 
                  {
                         Error = Error + '<li>' + "The Currency is invalid." + '</li>\n'
                     }
       }
0
Neil Smit
Top achievements
Rank 1
answered on 22 Aug 2012, 12:04 PM
Hi Phil

Where should I put the code for hooking up the events?
Thanks for this, been looking all over for cod to do this.
0
Phil
Top achievements
Rank 1
answered on 22 Aug 2012, 12:26 PM
Hi Neil

Here's a concrete example of one of my combo boxes

@(Html.Telerik().ComboBoxFor(x => x.ManufacturerGuid)

                                             .Name("ManufacturerGuid")

                                             .HighlightFirstMatch(true)

                                             .DataBinding(binding => binding

                                                 .Ajax()

                                                 .Select("_ListActiveManufacturerKeyValuePairs", "Manufacturer")

                                                 .Cache(false))

                                             .Filterable(filtering =>

                                             {

                                                 filtering.FilterMode(AutoCompleteFilterMode.Contains);

                                             })

                               .ClientEvents(events => events.OnLoad("ComboBox_OnLoadEnforce")

                                                             .OnClose("ComboBox_OnCloseEnforce"))

                                             )

0
Neil Smit
Top achievements
Rank 1
answered on 22 Aug 2012, 12:28 PM
Hi Phil

I'm not using MVC so I can't hook up events using
@(Html.Telerik().ComboBox()
0
Phil
Top achievements
Rank 1
answered on 22 Aug 2012, 12:59 PM
Ah,

This is a Telerik MVC controls forum. Try looking in the asp.Net web forms controls forum. You can probably use a similar technique to me.
Just use jquery to grab a reference to the control elements you need and minipulate them as required. The Telerik documentation is okay in parts.
Use this link http://www.telerik.com/community/forums/aspnet-ajax.aspx as your starting point.

Regards

Phil
0
chinh
Top achievements
Rank 2
answered on 06 Sep 2012, 02:55 AM
Thanks phil, This solution work fine but I still have a problem.
When I type and tab with normal speed, it work fine. However, when we type and tab very fast, combobox.selectedIndex return undefined at the first time and return index of previous selected if we have selected any item before. This is my app's fault or telerik combobox fault. Can you show me any online demo with this function to test this case.
Thanks alot. 
0
chinh
Top achievements
Rank 2
answered on 06 Sep 2012, 02:57 AM
Thanks phil, This solution work fine but I still have a problem.
When I type and tab with normal speed, it work fine. However, when we type and tab very fast, combobox.selectedIndex return undefined at the first time and return index of previous selected if we have selected any item before. This is my app's fault or telerik combobox fault. Can you show me any online demo with this function to test this case.
Thanks alot. 
Tags
ComboBox
Asked by
Julien
Top achievements
Rank 1
Answers by
Georgi Krustev
Telerik team
Julien
Top achievements
Rank 1
Phil
Top achievements
Rank 1
João
Top achievements
Rank 1
Abhiram
Top achievements
Rank 2
Neil Smit
Top achievements
Rank 1
chinh
Top achievements
Rank 2
Share this question
or