Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Multiselect dropdown list #52

Closed
grvgtm opened this issue Jan 7, 2013 · 33 comments
Closed

Multiselect dropdown list #52

grvgtm opened this issue Jan 7, 2013 · 33 comments
Labels

Comments

@grvgtm
Copy link

grvgtm commented Jan 7, 2013

I was wondering, how can I implement multiselect dropdown ??
Please suggest the best way to do multiselect dropdown in jTable. Looking forward to hear from you guys asap.

cheers!!
gaurav

@grvgtm
Copy link
Author

grvgtm commented Jan 8, 2013

I got the soln for it. Thanks.
We simply have to add a similar function like select dropdownlist(_createDropDownListForField) under jquery.jtable.js for multiselect then create a "field.type" for that function and call multiselect function under the 'field.type' 'else if" condition.


Ex.
// line number ~ 887 : field type for multiselect listbox
else if (field.type == 'multiselectddl') {
return this._createDropDownListMultiForField(field, fieldName, value);
}

// line number ~ 1000 : Function for Multiselect listbox
_createDropDownListMultiForField: function (field, fieldName, value) {
    //Create a container div
    var $containerDiv = $('<div class="jtable-input jtable-multi-dropdown-input"></div>');

    //Create multi-select element
    var $select = $('<select multiple="multiple" class="' + field.inputClass + '" id="Edit-' + fieldName + '" name=' + fieldName + '></select>').appendTo($containerDiv);

    //add options
    var options = this._getOptionsWithCaching(fieldName);
    $.each(options, function (propName, propValue) {
        $select.append('<option value="' + propName + '"' + (propName == value ? ' selected="selected"' : '') + '>' + propValue + '</option>');
    });

    return $containerDiv;
},

feel free to bug me..

cheers!!
gaurav

@hikalkan
Copy link
Member

hikalkan commented Jan 8, 2013

Thanks for your suggestion and solution :) I will add it to next versions of the jTable.

@xcalx9
Copy link

xcalx9 commented Jan 25, 2013

I attempted this as well as just using a custom input field. Both cases create the multi select when creating a record. But the AJAX post only sends the last selected value of the multi select (when more than one items are selected). I can't seem to figure out why. I think it should be sending "value1,value2,value3". Perhaps somewhere there needs to be an array instead of a regular variable. Thoughts anyone?

@hikalkan
Copy link
Member

I tested it. jTable sends all selected items. It's about your server side codes. See the post in chrome dev tools:

Clipboard01

jTable sends three CityId values to the server.

Also, to make a select dropdown as multiple, easy way is to use formCreated (http://jtable.org/ApiReference#event-formCreated) event:

formCreated: function(event, data) {
    data.form.find('select[name=CityId]').attr('multiple','multiple');
}

@galde
Copy link

galde commented Feb 5, 2013

Hello,

@hikalkan jtable is great! We have tried the code above but with no success :-( and we have made a little hack in order to accept a new type called multi, that is a select multiple.

With the purpose of respecting your great code, we have added in a different file this way:

Create a file called jquery.table.anadido.js with the following content:

$.hik.jtable.prototype._fillDropDownListWithOptions = function ($select,
options, value) {
var fieldName = $select.attr("name");
var field = this.options.fields[fieldName];
if (field.type == "multi") {
$select.empty().attr("multiple", "multiple");
for (var i = 0; i < options.length; i++) {
var selected = false;
for (var j = 0; j < value.length; j ++) {
if (value[j] == options[i].Value) {
selected = true;
break;
}
}
$select.append('<option value="' + options[i].Value +'"' +
(selected ? ' selected="selected"' : '') + '>' + options[i].DisplayText

  • '');
    }
    } else {
    $select.empty();
    for (var i = 0; i < options.length; i++) {
    $select.append('<option value="' + options[i].Value +'"' +
    (options[i].Value == value ? ' selected="selected"' : '') + '>' +
    options[i].DisplayText + '');
    }
    }
    };

Now, when you add jquery.jtable.js you have to add below this recently created file:

<script src=\"/jtable/jquery.jtable.anadido.js\" type=\"text/javascript\"></script>

And then when you define the structure:

                se_aplica_a_hosting: {
                    title: '" . _("Se aplica a hostings") . "',
                    list: false,
                    options: jtableHostings,
                    type: 'multi'
                },

Thank you very much and feel free for using and modifying this little hack.

@caca9512
Copy link

thanks for your work but the both method doesn't work with jquery.jtable.aspnetpagemethods.js. the record object only contain one object (string no string[]).

I will check for a solution...

have a good day.

@galde
Copy link

galde commented May 28, 2013

Hello,

What a pity! :-( I'm sorry. It is working for me properly, I hope you could
integrate correctly in your good software, because for me the multi-select
option is completely necessary.

Thank you in advance.

Yours,

2013/5/27 caca9512 notifications@github.com

thanks for your work but the both method doesn't work with
jquery.jtable.aspnetpagemethods.js. the record object only contain one
object (string no string[]).

I will check for a solution...

have a good day.


Reply to this email directly or view it on GitHubhttps://github.com//issues/52#issuecomment-18513926
.

Galder Segurola

Hostinet S.L

wget -O - http://www.hostinet.com/galder_hostinet.asc | gpg --import
Key fingerprint = EB35 6F3D 6DF1 C82B D4F5 E3AB A4CF 6411 6550 FA86

@caca9512
Copy link

hi galde, thank you for your quick response. Do you code in php or asp.net?

@galde
Copy link

galde commented May 28, 2013

Hello,

:-)

I code in php.net

Thanks in advance,

2013/5/28 caca9512 notifications@github.com

hi galde, thank you for your quick response. Do you code in php or asp.net
?


Reply to this email directly or view it on GitHubhttps://github.com//issues/52#issuecomment-18545131
.

Galder Segurola

Hostinet S.L

wget -O - http://www.hostinet.com/galder_hostinet.asc | gpg --import
Key fingerprint = EB35 6F3D 6DF1 C82B D4F5 E3AB A4CF 6411 6550 FA86

@caca9512
Copy link

Ok for all user of asp.net, i found the solution.
I hijack the _convertQueryStringToObject.
If the querystring from form.serialize contain the same key (like cityId of hikalkan exemple) i create a array.

I show you my file jtable.table.YOUNAME.js

$.hik.jtable.prototype._fillDropDownListWithOptions = function ($select, options, value) {
var fieldName = $select.attr("name");
var field = this.options.fields[fieldName];

if (field.type == "multi")
{
$select.empty().attr("multiple", "multiple");
for (var i = 0; i < options.length; i++)
{
var selected = false;
if (value != undefined)
{
for (var j = 0; j < value.length; j++)
{
if (value[j] == options[i].Value)
{
selected = true;
break;
}
}
}
else
{
selected = false;
}
//$select.append('<option ' + (selected ? ' selected = "selected" ' : '') + ' > ' + options[i].DisplayText + '');
$('<option ' + (selected ? ' selected = "selected" ' : '') + '>' + options[i].DisplayText + '').val(options[i].Value).appendTo($select);
}
}
else
{
$select.empty();
for (var i = 0; i < options.length; i++) {
//$select.append('<option ' + (options[i].Value == value ? ' selected="selected" ' : '') + '>' + options[i].DisplayText + '');
$('<option' + (options[i].Value == value ? ' selected = "selected"' : '') + '>' + options[i].DisplayText + '').val(options[i].Value).appendTo($select);
}
}
};

$.hik.jtable.prototype._convertQueryStringToObject = function (queryString) {
var jsonObj = {};
var e,
a = /+/g,
r = /([^&=]+)=?([^&]*)/g,
d = function (s) { return decodeURIComponent(s.replace(a, " ")); };

while (e = r.exec(queryString)) {
// alert(e);
// alert(d(e[1]));

if (jsonObj[d(e[1])] === undefined) {
  //alert(jsonObj[d(e[1])]);
  jsonObj[d(e[1])] = d(e[2]);
}
else {
  if (!(jsonObj[d(e[1])] instanceof Array)) {
    jsonObj[d(e[1])] = new Array(jsonObj[d(e[1])]);
  }

  jsonObj[d(e[1])][jsonObj[d(e[1])].length] = d(e[2]);
}

}

return jsonObj;
}

The object in my c# class is string[].

Good luck to all.

@caca9512
Copy link

ok cut and paste scrap code. Go to this url for see solution: https://gist.github.com/caca9512/5662735
Thanks

@cianpi1e
Copy link

Hi, does the code works for only when you select multiple options in the listbox? Because i'am having trouble when the user selects only one option.

@caca9512
Copy link

Working for the both case... I using MVC 3 with string[] property in my model.

@cianpi1e
Copy link

It's strange, I also have string[] in my model:
public string[] LineaIDArray { get; set; }

And i'm getting this error when the user selects only one option
Cannot convert object of type \u0027System.String\u0027 to type \u0027System.String[]\u0027

@caca9512
Copy link

Are you include <script type="text/javascript" src="/Scripts/jtable/external/json2.js"></script>
and do you use a third partie control in your application (like telerick)?
I test selected only one value and this is work great on my two applicaiton...

@cianpi1e
Copy link

I don´t use third party controls. What is the json you send in your form? When the user selects multiple options, jtable sends:

{"record":{"LineaIDArray":["15","16"]}}

but when selecting only one option, jtable sends it like a string:

{"record":{"LineaIDArray":"15"}}

when I think it should be sending it like string[]

{"record":{"LineaIDArray":["15"]}}

@caca9512
Copy link

same for me
{"record":{"Role":["Administrator","Sales"]}}

{"record":{"Role":"Administrator"}}

but in my mvc model Role variable contain a string[1]...
I don't know why does work for you!

Can you post controller code and Model code?

@cianpi1e
Copy link

this is my model's code

[Serializable]
public class AsignacionChild
{

public int vEmpleadoLineaID { get; set; }
public int LineaID { get; set; }
public string[] LineaIDArray { get; set; }
public string Linea { get; set; }
public double ALinea { get; set; }
public DateTime FechaInicio { get; set; }
public DateTime FechaFinal { get; set; }
public int Area { get; set; }

public AsignacionChild()
{
    vEmpleadoLineaID = 0;
    LineaID = 0;
    Linea = "";
    ALinea = 0.0;
    FechaInicio = DateTime.Now;
    FechaFinal = DateTime.Now;
    Area = 0;
}

public AsignacionChild(int vempleadolineaid, int lineaid, string linea, double alinea, DateTime fechainicio)
{
    vEmpleadoLineaID = vempleadolineaid;
    LineaID = lineaid;
    Linea = linea;
    ALinea = alinea;
    FechaInicio = fechainicio;
}

}

and this is my controller's code for the create action

[WebMethod]
public static object CreateAsignacionChild(AsignacionChild record, string EmpleadoID)
{
try
{
string Linea = ""; int vEmpleadoLineaID = -1;

        BonoDataSetTableAdapters.CreateAsignacionChildTableAdapter q = new      BonoDataSetTableAdapters.CreateAsignacionChildTableAdapter();
        BonoDataSet.CreateAsignacionChildDataTable t = new BonoDataSet.CreateAsignacionChildDataTable();
        for (int l = 0; l < record.LineaIDArray.Length; l++)
        {
            t = q.GetData(Convert.ToInt32(record.LineaIDArray[l]), EmpleadoID, record.FechaInicio);
            foreach (DataRow row in t.Rows)
            {
                vEmpleadoLineaID = Convert.ToInt32(row["vEmpleadoLinea"]);
                Linea = row["Linea"].ToString();
            }
            record.vEmpleadoLineaID = vEmpleadoLineaID;
            record.Linea = Linea;
            if (vEmpleadoLineaID == 0 || Linea == "0")
                throw new Exception("El empleado ya tiene asignada esa linea.");
        }
        return new { Result = "OK", Record = record };
    }
    catch (Exception ex)
    {
        return new { Result = "Error!!!!!!", Message = ex.Message };
    }
}

@prasanthchinna
Copy link

hi caca9512 your code is not working in Asp.net, can you provide me the comlete .js file for Asp.net c# not for MVC i.e, the script file you did changes. Can you please help me its urgent.

i m getting error as
{"Message":"Cannotconvertobjectoftype\u0027System.String\u0027totype\u0027System.String[]\u0027","StackTrace":"atSystem.Web.Script.Serialization.ObjectConverter.ConvertObjectToTypeInternal(Objecto,Typetype,JavaScriptSerializerserializer,BooleanthrowOnError,Object\u0026convertedObject)\

Thanks in advance

@caca9512
Copy link

prasanthchinna : https://gist.github.com/caca9512/5662735

@caca9512
Copy link

cianpi1e : Test with [HttpPost] no webMethod.

@prasanthchinna
Copy link

Thanks for your quick response, Can you give it in webMethod please. I m trying from past 3 days using webmethod but not getting

@cianpi1e
Copy link

prasanthchinna, I had the exact same problem as you, but I was getting this error because the post was sending a string, but the model was expecting a string[]. What is the code in your model?

@prasanthchinna
Copy link

Hi caca9512 you are giving "_convertQueryStringToObject " method may i know what for it

@prasanthchinna
Copy link

Hi hikalkan can you please provide us the code for asp.net webmethod, we are struggling a lot

stanleyta pushed a commit to stanleyta/jtable that referenced this issue May 6, 2014
Used in ASP.NET MVC
To use, set the type on the field to 'multiselectddl'.
The options dropdown will become a select. Data is treated as comma delimited.

Based off of info from:
volosoft#52
@maryum426
Copy link

@grvgtm Hi gaurav .... can you please tell me what does this function do ?? 'getOptionsWithCaching(fieldName)' ??

@caca9512
Copy link

caca9512 commented Jul 7, 2014

hi maryum426, this function return a array on value id you use a multiselect dropdown (jtable type :multi).
This solution work only with MVC, not asp.net form.
thanks.

@maryum426
Copy link

@caca9512 got it .... Thanks

@maryum426
Copy link

@caca9512 @hikalkan I was wondering what should be the return format of the data with a field having multiple values so that when we open the Edit Form they would already be selected?

@pash7ka
Copy link

pash7ka commented Aug 29, 2014

I had to do some modifications to current https://github.com/stanleyta/jtable/blob/master/lib/jquery.jtable.js
here is the diff:

751c751,755
<                 return this._findOptionByValue(options, fieldValue).DisplayText;
---
>                 if(field.type == 'multiselectddl'){
>                     return this._findOptionDisplayTextByValueMultiselect(options, fieldValue);
>                 } else { 
>                     return this._findOptionByValue(options, fieldValue).DisplayText;
>                 }
783c787,798
< 
---
>         /* Finds options object by given value for multiselectddl field and returns their DisplayText
>         *************************************************************************/
>         _findOptionDisplayTextByValueMultiselect: function (options, value) {
>             var values = value.split(",");
>             if(values.length == 1) return this._findOptionByValue(options, value).DisplayText;
>             var result = "";    
>             for (var i = 0; i < values.length; i++) {
>                 if( i > 0) result += ", ";
>                 result += this._findOptionByValue(options, values[i]).DisplayText;
>             }
>             return result;
>         },
1561c1576
<                 return this._createDropDownListMultiForField(field, fieldName, value);
---
>                 return this._createDropDownListMultiForField(field, fieldName, value, record);
1697c1712
<         _createDropDownListMultiForField: function (field, fieldName, value) {
---
>         _createDropDownListMultiForField: function (field, fieldName, value, record) {
1704c1719,1724
<             var options = this._getOptionsForField(fieldName);
---
>             var options = this._getOptionsForField(fieldName,{
>                     record: record,
>                     value: value,
>                     source: 'list',
>                     dependedValues: this._createDependedValuesUsingRecord(record, field.dependsOn)
>             });

To use this I have the following code:

    $('#MyTable').jtable({
            title: 'MyTableWithMultiSelectDDL',
            actions: {listAction: '...',createAction: '...',updateAction: '..',deleteAction: '...'},
            fields: {
                id: {key: true,list: false},
                simpleField: {title: 'simpleField'},
                multiselectField: {
                    title: 'multiselectField,
                    type: 'multiselectddl',
                    options: 'http://....'
                }
            },
            formSubmitting: function(event,data){
                $('select[name=multiselectField]', data.form).attr('name','multiselectField[]');
                return data;
             }
    });

This formSubmitting hook is required since my PHP backend only uses the last value from several selected if variable name does not have [] in the end.

@graps
Copy link

graps commented Aug 20, 2015

hi pash7ka, I tried your solution but the dependsOn still wouldn't work. Has the support for the jquery jtable stopped? I just downloaded the latest update from the link specified on the site and I didn't find an implementation for the multiple select and a dependsOn attribute. This is really a big flaw of the jtable. Presently, I am looking for a workaround for this problem because I have seen no straight forward solution to this problem.

@mandeepdevgan
Copy link

Hi,
In my case I have achieved multiselect drop down,but my problem is how to show multiple default selected values in edit event for same dropdown.

@shelleyvs
Copy link

shelleyvs commented Oct 6, 2017

"multi-select" in jQuery jTable working fine. I save it as comma separated values. How to display multiple selected values while editing ??

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests