jqGrid Dynamically loading select options


Scenario:
You are using the jqGrid to edit rows that contain fields that are of HTML tag type "SELECT".


Problem: You do not want to hard code the values of the select tag like in the jqGrid samples. For example:

editoption: { value: "FE:FedEx; IN:InTime; TN:TNT" }


Solution: For example to load a list of countries dynamically, define the variable before the definition of the jqGrid:


//get all countries
var countries = $.ajax({url: $('#ajaxAllCountriesUrl').val(), async: false, success: function(data, result) {if (!result) alert('Failure to retrieve the Countries.');}}).responseText;



Now define your jqGrid:

$(yourgrid).jqGrid({
...
colModel: [
{ name: 'Id', index: 'Id', width: 20, sortable: true, align: "center", editable: false, editoptions: { readonly: true, size: 0 }, search: true },

{ name: 'Country', index: 'Country', width: 80, sortable: true, editable: true, edittype: "select", editrules: { required: true }, editoptions: { size: 71} }
],
...
loadComplete: function() {
$(yourgrid).setColProp('Country', { editoptions: { value: countries} });
},
...

Important: The ajax call to retrieve the countries must be set to "async: false" otherwise you have a very good chance that the grid will be defined before the data is actually returned. Using the same logic you can reload the list based on some other event and trigger the reload of the grid if need be to reload the new list.

 

The format of the country object is a JSON object and looks like this:

{"Countries":{"Content":"230:UNITED STATES;40:CANADA;7:AFGHANISTAN; etc.....   }}

Print | posted @ Thursday, July 2, 2009 11:14 AM

Comments on this entry:

Gravatar # re: jqGrid Dynamically loading select options
by shiva at 7/15/2009 3:23 AM

if multiple drop downs is there fil like this with onchange event

$( '#'+id+'_clients' ).change( function(){
iCustomerID = $(this).val();
var objProjectsList = getProjectsList( iCustomerID );
var objProjectsDropDown = $(this).parent('td').next().find('select');
$( objProjectsDropDown ).empty();

$( objProjectsDropDown ).append( '<option value="0">--Select projects--</option>' );

for( strIndex in objProjectsList )
{
$(objProjectsDropDown).append( '<option value="' + objProjectsList[strIndex].ProjectId + '">' + objProjectsList[strIndex].ProjectName + '</option>' );
}


$(objProjectsDropDown).unbind('change');

// Fill the ActivitesDropDown with dynamic data
$(objProjectsDropDown).change(function(){
iProjectId = $(this).val();
var objActivitiesList = getActivitesList( iCustomerID, iProjectId );
var objActivitiesDropDown = $(this).parent('td').next().find('select');
$(objActivitiesDropDown).empty();
$( objActivitiesDropDown ).append( '<option value="0">--Select activites--</option>' );
for( strIndex in objActivitiesList )
{
$(objActivitiesDropDown).append( '<option value="' + objActivitiesList[strIndex].ActivityId + '">' + objActivitiesList[strIndex].ActivityName + '</option>' );
}
$(objActivitiesDropDown).unbind('change');

$(objActivitiesDropDown).change(function(){
iActivityId = $(this).val();
});
});
});
Gravatar # re: jqGrid Dynamically loading select options
by Renso at 7/15/2009 2:29 PM

Shiva I am not sure if I understand your question but it seems you have drop down dependencies and yes can you do it this way. There is a short way to load SELECT tags via ajax requests using the selectboxes plug-in: http://www.texotela.co.uk/code/jquery/select/:

objActivitiesDropDown.removeOption(/./).ajaxAddOption(getProjectsList( iCustomerID ), null, false).addOption({ '': '--Select activites--' });

This will clear the existing list as well as load the new dependent list as well with one line of code.

When you are using jqGrid and edit the records in form edit mode (meaning in the modal dialog box) then you would do it like you have specified above or using the example I have here, but you will need to specify the bind in the navGrid callback functions like so (only show the edit options here for brevity but you will need to do the same for add options also):

.navGrid(item + 'Pager',
{ refresh: true, edit: true, add: true, del: true, search: false }, //options
{height: 280, width: 500,
reloadAfterSubmit: true,
modal: true,
processData: 'Updating the Project...',
editCaption: 'Edit a Project',
beforeShowForm: function() {
objActivitiesDropDown.removeOption(/./).ajaxAddOption(getProjectsList( iCustomerID ), null, false).addOption({ '': '--Select activites--' });

}
}, // edit options

Please let me know if this answers your question. Also thank you for your sample of code here, without the selectboxes plug-in ths will come in very handy :-)




Gravatar # re: jqGrid Dynamically loading select options
by shiva at 7/16/2009 6:07 AM

hi, renso
I forgot to right the comments at last ,
my problem is u understood the scenario multiple dropdowns clients,projects,activites all are filling with denpedency with previous one.

I want the option is in selected mode when i try to edit the record in projects, activites dropdowns(the items existing in non editable mode)

thanks
renso,
Gravatar # re: jqGrid Dynamically loading select options
by Andrew Shansky at 9/23/2009 5:42 PM

Hey Thanks for posting this article.

I have one page where the dropdown options are listed and can be added to/removed/edited by the user. On another page I have a grid that uses two selects that pull their data from the other pages using the method you suggested. However my problem is that if I go to the parent page, and then go and add an option on the other pages, the parent grid does not up date when i go to edit or add a new record. Is there any way to force the grid to update it's data?

thanks
Andrew
Gravatar # re: jqGrid Dynamically loading select options
by Renso at 9/24/2009 7:27 AM

To refresh a grid without destroying it an redefining it is to trigger the built-in grid refresh when the drop down changes. I am assuming when you say "parent page" you mean the same web-page but in a different part of the web-page. Here is an example:

$(objActivitiesDropDown).change(function(){
$('#myGrid').trigger('reloadGrid');
});

Gravatar # re: jqGrid Dynamically loading select options
by pandu ranga rao at 10/20/2009 8:05 AM

hi i solved the above problem here is the code to load the jqgrid dynamically for onchange event

$("#prod_code").change(function(){
var p_c=document.getElementById("prod_code").value;
$('#list2').setGridParam({url:"gdata.php?q=1&prod_code="+p_c,page:1});
$('#list2').trigger('reloadGrid');
});

Gravatar # re: jqGrid Dynamically loading select options
by Neel at 3/2/2010 4:00 AM

Hey Renso,

Do u have any samples where we have mulitpleSearch filters available (With MVC pattern) ?

I saw some samples which uses SQL LINQs (using I/f IQueryable) But i was looking for some scenario where
can filter an array using the search parameters.

It will be greatly appreciated if you provide any working samples for above mentioned scenario.

Thanks,

Neel
Gravatar # re: jqGrid Dynamically loading select options
by wawan b. setyawan at 11/7/2010 10:13 AM

i've tried the code but it won't work.. so please tell me what should #ajaxAllCountriesUrl fills with? the url to the php file which retrieving select's option value from mysql?
Gravatar # re: jqGrid Dynamically loading select options
by TMK at 12/13/2010 12:33 AM

how should the 'countries' be structured ?
I am calling a controller say a servlet which is going to hit DB and return the list of countries to me.. in this case how should I return the countries so that the select box can be populated.
Thanks a lot for help in advance.
Gravatar # re: jqGrid Dynamically loading select options
by Renso at 12/13/2010 3:09 PM

Blog updated with format of countries. Not pure JSON format though, jqGrid takes a custom format that looks somewhat like JSON, semi-colon delimited.
Gravatar # re: jqGrid Dynamically loading select options
by rohith at 3/4/2011 5:47 AM

Hey Renso,
Need a small help.
This article demonstrates how we can reload a grid on some events.
I have a similar requirement as posted by Andrew.
The page has a 2 grids.Assume the first grid is a state grid and the second grid is a state-city mapping grid.
Now when I add a state in the 1st grid it gets added in the db and the 2nd grid has a select which will populate the data from a URL(this url fetches frm DB).
Now the problem is when I add a new record to the state it doesnt immediately populate in 2nd grid as the URL where the 2nd grid is populating data from is already initialized..i.e,it is populating the select drop down only once whn the initial grid is loaded...after that when ever we click on add,edit it jus shows the same data which it has already fetched.

Please let me know if u have ny solution for this,.


Thanks
Rohith
Gravatar # re: jqGrid Dynamically loading select options
by Renso at 3/7/2011 8:36 AM

Rohith, the second grid needs to be reloaded (do grid trigger('reloadGrid')) and/or if you set the lookup list outside of the grid you will need to add the ajax request to get the latest states lookup to the second grid like this:
$(grid).trigger('reloadGrid') and then in gridComplete event:
$(grid).setColProp('States', getJson) - of course I am paraphrasing a bit here. The getJson will fetch the new state from DB. Remember, the way the grid is designed is to get the look-up data once for performance reasons, and to get it to reload it you need to reload the grid.
Gravatar # re: jqGrid Dynamically loading select options
by Hernan at 3/15/2011 9:23 AM

Great. Can you please upload a working example of this? or, maybe post the controller code? I get the values but not in the correct format, I see everything in json format... this is my controller code.
public ActionResult GetSponsors()
{
var context = new Models.SQLDataDataContext();
var jsonData = new
{
rows = (
from sponsor in context.Sponsors
select new{
cell = new string[]
{
sponsor.Id.ToString(),
sponsor.Nombre
}
}).ToArray()
};
return Json(jsonData, JsonRequestBehavior.AllowGet);
}

Thanks!
Gravatar # re: jqGrid Dynamically loading select options
by marko at 3/23/2011 7:53 AM

Hello,
I'm having problems implementing the dynamic dropdown menu using jqGrid and CodeIgniter.

How can I load a JSON object into the grid (as dropdown key-value pairs)?
Also, I have more than one dropdown menu per grid. Does this make any difference?

This is my JSON:
{"rows":[{"id":"5","cell":["5","Manifactured"]},{"id":"6","cell":["6","Purchased"]},{"id":"8","cell":["8","Other"]}]}
Gravatar # re: jqGrid Dynamically loading select options
by Vikas Yadav at 4/17/2011 4:06 AM

I have one dropdown and I want to handle the SelectedIndexChanged event using JQuery. Is there any way to achieve this? Any sample code would be more helpful...
Gravatar # re: jqGrid Dynamically loading select options
by Max at 8/9/2011 7:06 PM

What is the value of '#ajaxAllCountriesUrl'
I'm using MVC 3. Is it something like '/Home/Lookup/'?
Gravatar # re: jqGrid Dynamically loading select options
by Renso at 8/11/2011 8:46 AM

'#ajaxAllCountriesUrl' is a hidden input HTML tag that I set in my master page or any other aspx page in .Net to - in the particular example - store the url of the controller/action in MVC. I did not want to hard-code any url paths so I generate them on the fly based on the routing module in MVC's routing:

<input id="ajaxAllCountriesUrl" type="hidden" value="<%=Url.RouteUrl(new {controller = "Ajax", Action = "GetAllCountries"})%>" />
Gravatar # re: jqGrid Dynamically loading select options
by atul at 11/9/2011 8:11 AM

guys, i think this is the similer problem which i am facing , can someone upload a sample code where jqgrid have multiple select filter option. that would be great help man.... thanks in advance
Gravatar # re: jqGrid Dynamically loading select options
by atul at 11/9/2011 8:19 AM

guys, i think this is the similer problem which i am facing , can someone upload a sample code where jqgrid have multiple select filter option. that would be great help man.... thanks in advance
Gravatar # re: jqGrid Dynamically loading select options
by atul at 11/9/2011 8:20 AM

guys, i think this is the similer problem which i am facing , can someone upload a sample code where jqgrid have multiple select filter option. that would be great help man.... thanks in advance
Gravatar # re: jqGrid Dynamically loading select options
by arham at 8/6/2013 4:00 AM

hello
how to get selected text from the dropdownlist

pliz help
Post A Comment
Title:
Name:
Email:
Comment:
Verification:
 
Twitter