Was coding some new functionality and though I would post this, so that others can find it helpful.
Lets say you have a form that has a checkbox that will update the select dropdown box with different values, when the checkbox is clicked.
Something like the UI below.
Your html code might look like
1 2 3 4 5 6 7 8 |
<input type="hidden" name="fieldId" value="123" /> Parent: <select name="FieldType" id="fieldTypeDropDown"> <option value="16">None</option> <option value="4">Apple</option> <option value="3">Orange</option> </select> Multiple: <input type="checkbox" name="fieldMultiple" id="fieldMultiple" /> |
On your server side you would provide a Action Method to filter out the data, something like
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
[HttpGet] public JsonResult GetParents(int parentId, bool isMultiple) { //get from the database or something which is calling the possible parents List<ParentViewModel> result = GetPossibleParents(parentId, isMultiple); IDictionary<string, string> dictionary = new Dictionary<string, string> {{"-1", "None"}}; foreach(ParentViewModel item in result) { dictionary.Add(item.Id.ToString(), item.Name); } return Json(dictionary, JsonRequestBehavior.AllowGet); } |
Now we got to add the javascript to listen to the checkbox event changed, something like this in jquery, since we are getting Json Result we will have to parse the json object to populate the dropdown box.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
$('#fieldMultiple').live('change', function() { var fieldId = $('#fieldId').val(); var isMulti = false; if ($(this).is(':checked')) { isMulti = true; } //call ajax now $ajax( {type: "POST", url: "someurl", data: { parentId: fieldId, isMultiple: isMulti}, success: function(data){ var dropDown = $('#fieldTypeDropDown'); //remove all the children dropDown.children().remove(); //add the new children $.each(data, function(key, value) { dropDown.append('<option value="' + key + '">'+ value +"</option>"); }); //create an effect to show its updated dropDown.effect('shake', {times: 4}, 100); } }); } }); |
By doing so you will have something that shakes and updates the drop down box by some simple ajax calls 🙂
[…] the select dropdown box with different values, when the checkbox is clicked. Something like… [full post] taswar Taswar Bhatti Blog jqueryaspmvc 0 0 0 0 0 […]
Thanks dude! Very useful.