Trigger change and selection in select2 populated by ajax - jquery-select2

I m populating my select2 using ajax with processResults function as in this code,
function PopulateSelect2(sqlclass, ControlID, PlaceHolder) {
$('#' + ControlID).select2({
placeholder: PlaceHolder,
allowClear: true,
theme: "bootstrap",
ajax: {
type: "POST",
url: "../Web_Services/Common/Controllers.asmx/populateCtls",
contentType: "application/json; charset=utf-8",
dataType: "json",
//delay: 250,
data: JSON.stringify({ selector: sqlclass, subselector: '' }),
processResults: function (data) {
var parsed = JSON.parse(data.d);
console.log(parsed)
return {
results: parsed
};
}
},
});}
and I call this function in this way,
$(document).ready(function () {
PopulateSelect2("ddl_occupation", "AddrStateID", "Select")
});
I am trying to set the value after by triggering change but its not working
I tried the following,
$('#AddrStateID').val(4).trigger('change.select2');
I managed to trigger selection inside the list but without showing the value in theselectelement control using this code
$("#AddrStateID").select2("trigger", "select", {
data: { id: "4" }
})
is there a way to trigger the selection and show the result in the select control?

So in i worked around it by pre-populating my select control by ajax call but not by using select2 - ajax call
I added the following attributes to each select control
parent="" param="" child="" placeholder="" aval=""
Where,
parent: represents the parent id selector,
param: represents the control's data parameter that I use for ajax call,
child: represents the control's child control id selector,
placeholder: represents the control's placeholder,
aval: represents the control's assigned value in case wanted to be populated and selected because I use my form for storing data and reading data as well.
in the following example I have 3 select cascade controls.
<div class="panel-body">
<div class="col-xs-12">
<div class="form-grobtn row">
<label class="col-sm-2 col-form-label">File Grobtn</label>
<div class="col-sm-10">
<select id="GpId" style="width: 100%"
class="form-control populate" name="GpId" parent="" param="ddl_btnldgp" child="#CatId"
placeholder="File Grobtn..."
aval="">
<option></option>
</select>
</div>
</div>
<div class="form-grobtn row">
<label class="col-sm-2 col-form-label">File Category</label>
<div class="col-sm-10">
<select id="CatId" style="width: 100%"
class="form-control populate" name="CatId" parent="#GpId" param="ddl_btnldcat"
placeholder="Select File Category..."
child="#CatDtlId" aval="">
<option></option>
</select>
</div>
</div>
<div class="form-grobtn row">
<label for="inputPassword3" class="col-sm-2 col-form-label">File Type</label>
<div class="col-sm-10">
<select id="CatDtlId" style="width: 100%"
class="form-control populate" parent="#CatId" param="ddl_btnldcatdtl" child=""
placeholder="Select File Type..."
aval="">
<option></option>
</select>
</div>
</div>
</div>
</div>
<button id="btn" class="btn cUpldBtn btn-success" type="button">
Assign</button>
And Are being populated using this function
function populateddl(ctl) {
var $this = $(ctl);
var parent, param, child, aval
parent = $this.attr('parent');
placeholder = $this.attr('placeholder');
child = $this.attr('child');
$(child).prop("disabled", true);
param = $this.attr('param');
aval = $this.attr('aval');
if (!parent) {
$.ajax({
type: "POST",
url: "../Web_Services/Common/Controllers.asmx/populateCtls",
data: JSON.stringify(obj = {
selector: param,
subselector: null
}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
var jsonData = JSON.parse(data.d);
$this.html('').append('<option>')
$(child).prop("disabled", true)
$this.select2({
data: jsonData,
placeholder: $this.attr('PlaceHolder'),
allowClear: true,
theme: "bootstrap"
});
if (aval) { $this.val(aval).trigger('change'); $this.attr('aval',''); }
},
})
}
$this.change(function () {
if ($this.val() && child) {
$.ajax({
type: "POST",
url: "../Web_Services/Common/Controllers.asmx/populateCtls",
data: JSON.stringify(obj = {
selector: $(child).attr('param'),
subselector: $this.val()
}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
var jsonData = JSON.parse(data.d);
$(child).html('').append('<option>')
$(child).prop("disabled", false)
$(child).select2({
data: jsonData,
placeholder: $(child).attr('PlaceHolder'),
allowClear: true,
theme: "bootstrap"
});
if ($(child).attr('aval')) { $(child).val($(child).attr('aval')).trigger('change'); $(child).attr('aval', ''); }
},
})
} else {
$(child).html('').append('<option>').prop("disabled", true).trigger('change');
}
})}
Only parents (including childs that are parent to sub select controls) are called using function populateddl(ctl)
in this example I populate as following,
$(document).ready(function () {
populateddl('#GpId');
populateddl('#CatId');
})
In order to assign values, I need to populate and select the value afterwords for child controls,
$(document).ready(function () {
$("#btn").click(function () {
$('#GpId').val(1).attr('aval', '1').trigger('change', 'select2');
$('#CatId').val(2).attr('aval', '2').trigger('change', 'select2');
$('#CatDtlId').val(1).attr('aval', '1').trigger('change', 'select2');
return false;
})
})

Related

C# razor select2 disable

Is there a way I can set this select2 to be disable read-only if there is a value in option.AgentName? I have add the selectElement.select2 method is there anything I can add to the callback?
Is this the correct way to do this? using self.entry.Agent.AgentName != ""?
View
<div class="form-group sentence-part-container sentence-part ng-scope ui-draggable sentence-part-entry-agent sentence-part-with-select2-single" [class.has-errors]="entry.IsInvalid && entry.IsTouched">
<div class="sentence-part-values">
<div class="sentence-part-values-select2-single">
<select class="form-control" style="width: 300px" [(ngModel)]="entry.Agent.VersionKey">
<option *ngFor="let option of agents" [value]="option.VersionKey">{{option.AgentName}}</option>
</select>
</div>
</div>
</div>
ts file
$selectElement.select2({
initSelection: function(element, callback) {
console.log(self.entry.Agent.AgentName);
if (self.entry.Agent.AgentName != "")
{
console.log('disabled');
$selectElement.prop('disabled', true);
}
callback({ id: self.entry.Agent.VersionKey, text: self.entry.Agent.AgentName });
},
placeholder: "Select an agent"
})
.on("change", (e) => {
self.ngZone.run(() => {
self.entry.Agent.VersionKey = $selectElement.val();
self.entry.AgentVersionKey = self.entry.Agent.VersionKey;
let regimenEntryAgent = this.getRegimenEntryAgentByVersionKey(self.entry.Agent.VersionKey);
if (regimenEntryAgent) {
self.entry.Agent.AgentId = regimenEntryAgent.AgentId;
}
self.onSentenceChange(null);
});
})
.on("select2:close", () => {
self.entry.IsTouched = true;
this.validate();
});
You might try to apply some logic in newData.push() method of Select2.
ajax: {
url: '/DemoController/DemoAction',
dataType: 'json',
delay: 250,
data: function (params) {
return {
query: params.term, //search term
page: params.page
};
},
processResults: function (data, page) {
var newData = [];
$.each(data, function (index, item) {
// apply some logic to the corresponding item here
if(item.AgentName == "x"){
}
newData.push({
//id part present in data
id: item.Id,
//string to be displayed
text: item.AgentName
});
});
return { results: newData };
},
cache: true
},
Update:
It is recommended that you declare your configuration options by passing in an object when initializing Select2. However, you may also define your configuration options by using the HTML5 data-* attributes.
For the other Select2 options look Options.

Select2 initSelection element Val

I am using the select2 control on my web aplciation. In the initSelection I am passing the element.val() to a controller but it is null. How would I set element.val() that i want pass to the Url.Action. Is element.val() the correct object that I should be using when I am using a div?
I see the value in Chrome
debugger
view
<div id="guideline-container" style="#(Model.Type == "Guideline" ? "display:block" : "display:none")">
<form id="guideline-form" class="form-horizontal">
<div class="form-group">
<label for="guidelineName" class="col-sm-2 control-label">Guideline</label>
<div class="col-sm-10">
<div id="guidelineName">
#{ Html.RenderAction("Index", "GuidelinesPicklist", new { value = Model.GuidelineId, leaveOutAlgorithmItems = true, separateActiveItems = true }); }
</div>
<div class="guideline-not-selected field-validation-error" style="display: none;">
Guideline is required.
</div>
</div>
</div>
<div class="text-center">
<button type="submit" class="btn btn-primary modal-submit-btn">Add</button>
<button type="button" class="btn btn-default modal-close-btn" data-dismiss="modal">Close</button>
</div>
</form>
</div>
function
$(this).select2({
placeholder: "#Model.Settings.Placeholder",
//allowClear: true,
ajax: {
url: "#Url.Action("GetPicklistItems")",
contentType: 'application/json; charset=utf-8',
type: 'POST',
dataType: 'json',
data: function (params) {
return JSON.stringify({
query: params.term,
args: #Html.Raw(JsonConvert.SerializeObject(#Model.Settings != null ? #Model.Settings.AdditionalArguments : null))
});
},
processResults: function (data, page) {
console.log("processResults");
console.log(data);
var resultData = [];
if (isError(data)) {
showErrorMessage(getErrorMessage(data));
} else {
hideErrorMessage();
mapResultData(data.Result, resultData, 0);
}
return {
results: resultData
};
}
},
templateResult: format,
templateSelection: function(data) {
return data.text;
},
initSelection: function (element, callback) {
//console.log("initSelection");
//var id = $(element).val();
//console.log(id);
var guidelineId = "#Model.Value";
console.log("guidelineId");
console.log(guidelineId);
//console.log("params");
//console.log(params);
//console.log("element object Text");
//console.log(element.text);
debugger;
getAjax("#Url.Action("GetPicklistItem")" + "?value=" + guidelineId, function (result)
{
console.log("Ajax GetPicklistItem");
console.log(result);
debugger;
if (result.Result) {
var data = {};
$.extend(data, result.Result);
data.id = result.Result.Value;
data.text = result.Result.Text;
callback(data);
self.trigger("picklistChanged", data);
} else {
console.log(result);
debugger;
callback ({ id: null, text: "#Model.Settings.Placeholder" })
}
});
},
escapeMarkup: function(m) {
return m;
}
}).on('change', function () {
var data = self.select2('data');
self.trigger("picklistChanged", data);
});
You can get Select2 selected value or text by using the following approaches:
var selectedValue = $('#Employee').val();
var selectedText = $('#Employee :selected').text();
Alternatively you can simply listen to the select2:select event to get the selected item:
$("#Employee").on('select2:select', onSelect)
function onSelect(evt) {
console.log($(this).val());
}

Jquery UI selectable: Define multiple selectable objects DYNAMICALLY

I really need some help on the following: I am currently developing a shopping cart. Whenever a new product is appended to shopping cart it becomes a button. This button (product) is used to add some modifiers to each product. The button definition can be seen below:
var productAdded = $('<tr class="product" data-real_id = "'+ id +'" data-id_modal="'+ mod_id +'"><td class="product_name2"><button href="#0" class="button2" style="background-color:#00a65a;" data-comment="" data-modifiers="" data-span_mod = "" data-real_id = "'+ id +'" data-id_modall="'+ mod_id +'" id = "'+ comment_id +'">' + product_name + '</button></td><td class="quantity"><span class="select"><select id="cd-product-'+ id +'" name="quantity"><option value="1">1</option><option value="2">2</option><option value="3">3</option><option value="4">4</option><option value="5">5</option><option value="6">6</option><option value="7">7</option><option value="8">8</option><option value="9">9</option></select></span></td><td class="price">' + product_price + '</td><td><i class="fa fa-trash-o fa-2x" aria-hidden="true"></i></td></tr>');
Whenever each of the product's button is pressed a JQUERY UI dialog window is opened whic contains a JQUERY UI SELECTABLE object:
<div class="modal fade" id="modal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header"></div>
<div class="modal-body" style="margin-top:5px;">
<div style="width:100%; float:left;">
<label for="modifier">Τροποποιητές: </label>
<span id="select-result" data-modifiers_span=""></span>
<ol id="selectable" class="txt-modifiers">
<!-- INSERTED BY JQUERY DYNAMICALLY PER PRODUCT -->
</ol>
</div>
<label for="comment">Σχόλιο: </label>
<textarea rows="4" cols="50" name="comment" id="comment" value="" class="form-control txt-comment" style="vertical-align: top;"></textarea>
</div>
<div class="modal-footer" style="margin-top:10px;">
<button class="btn btn-success btn-save" data-id="" data-id_modall="">Αποθήκευση</button>
<button class="btn btn-default" data-dismiss="modal">Κλείσιμο</button>
</div>
</div>
</div>
</div>
As you can see below the modifiers of the product are extracted using AJAZ+PHP from mysql database:
$(document).on('click touchstart','.button2',function(e){
e.preventDefault();
var id = $(this).attr('id'); //Get element id
var real_id = $(this).attr('data-real_id');
var comment = $(this).attr('data-comment'); //Get comment
var modifiers = $(this).attr('data-modifiers'); //Get modifiers
var teeee = $(this).attr('data-id_modall');
$('#modal .txt-comment').val(comment);
$('#modal .btn-save').attr('data-id',id);
$('#modal .btn-save').attr('data-id_modall',teeee);
//alert(modifiers);
if (modifiers.length == 0)
{
$("#selectable").html('<img src="images/ajax-loader.gif" />');
var request = $.ajax({
url: 'http://127.0.0.1:8080/Food%20Ball/backup/FoodBall%20Site%20form_dt_2/Food%20Ball%20Site/get_item_modifiers.php?item_id=' + real_id,
cache: false,
dataType: 'json',
contentType: 'application/json; charset=utf-8',
type: 'get',
success: function(data) {
if( data.result != 'Not'){
$("#selectable").html(data.options);
$('#modal .txt-modifiers').val(data.options);
}
else{ $("#selectable").html('Δεν υπάρχουν!');
$('#modal .txt-modifiers').val('Δεν υπάρχουν!'); }
}
});
}
else { $('#modal .txt-modifiers').val(modifiers); $("#selectable").html(modifiers);}
$('#modal').dialog('open');
});
And the selectable object:
$(function () {
$('#selectable').on('touchstart mousedown', function(e) {e.metaKey = true;})
.selectable({
selected: function(event, ui) {
var result = $( "#select-result").empty();
$( ".ui-selected", this ).each(function() {
result.append($(this).attr('data-product_modifier') + ', ');
});
},
unselected: function(event, ui){
var result = $( "#select-result");
$( ".ui-unselected", this ).each(function() {
result.remove($(this).attr('data-product_modifier') + ', ');
});
}
});
});
And finally the "Save" button for each dialog modal window:
$(document).on('click touchstart','.btn-save',function(e){
e.preventDefault();
var id =$(this).attr('data-id'); //Get data id
var comment =$('.txt-comment').val(); //get the comment
var modifiers =$('.txt-modifiers').val(); //get the modifier
//update the "order" note column modal
var note_modal = '#' + $(this).attr('data-id_modall'); //get the id row of the order modal
var note_modal2 = '#2' + $(this).attr('data-id_modall'); //get the id row of the order modal
$(note_modal).find('#note_modal').text(comment+'--'+modifiers);
$(note_modal2).find('#note_modal2').text(comment+'--'+modifiers);
$('#'+id).attr('data-comment',comment);
$('#'+id).attr('data-modifiers',modifiers);
//Save it in data base..s
$('#modal').dialog('close');
$('.txt-comment').val('');//clear text area
$('.txt-modfiers').val('');//clear text area
});
$(document).on('click','.btn-default',function(e){
e.preventDefault();
//Save it in data base..s
$('#modal').dialog('close');
$('.txt-comment').val('');//clear text area
$('.txt-modfiers').val('');//clear text area
});
My problem is that if i add more than one products to my cart the selected modifiers appear for all products. How can i have multiple selectable objects defined dynamically and save each product's selected modifiers?
If anyone can help on this i will really appreciate it
Thank you
ok solved it:
simply put the following code within the successful return of the Ajax call:
var request = $.ajax({
url: 'http://127.0.0.1:8080/Food%20Ball/backup/FoodBall%20Site%20form_dt_2/Food%20Ball%20Site/get_item_modifiers.php?item_id=' + real_id,
cache: false,
dataType: 'json',
contentType: 'application/json; charset=utf-8',
type: 'get',
success: function(data) {
if( data.result != 'Not'){
$("#selectable").html(data.options);
$('#modal .txt-modifiers').val(data.options);
$( "#selectable" ).selectable({
stop: function() {
result_mod = $( ".select_result" ).empty();
$( ".ui-selected", this ).each(function() {
result_mod.append(' +' + $(this).attr('data-product_modifier'));
//array_mod = array_mod + (' +' + $(this).attr('data-product_modifier'));
$('#modal .select_result').val(result_mod);
});
}
});
}
else{ $("#selectable").html('Δεν υπάρχουν!');
$('#modal .txt-modifiers').val('Δεν υπάρχουν!');
$( ".select_result").html('');
$('#modal .select_result').val('');
}
}
});

How can I get the id's of a draggable and droppable element when using jquery UI?

I am trying to use the code below to trigger an ajax request when I drop a dragged element, but it doesn't work. I think it's because I'm not actually getting the id's, but I'm not sure.
HTML:
<div class="draggable">item 1</div>
<div class="draggable">item 2</div>
...
<div class="droppable">drop location 1</div>
<div class="droppable">drop location 2</div>
...
jQuery:
$(document).ready(function() {
$(".draggable").draggable({cursor: 'move', helper: 'clone'});
var ID1 = $(".draggable").attr(id);
var ID2 = $(".droppable").attr(id);
$(".droppable").droppable({
drop: function() {
$.ajax({
type: "POST",
url: 'www.mydomain.com/'+ID1+'/'+ID2,
dataType: 'html',
success: function(){}
});
return false;
}
});
});
ajon's answer is not quite right - both ID1 and ID2 relate to the target (where the dragged element has been dropped), whereas the question asks for id's of both dragged and dropped elements.
given modified html of (as per question but with added id's for all elements)
<div class="draggable" id="item1">item 1</div>
<div class="draggable" id="item2">item 2</div>
...
<div class="droppable" id="drop1">drop location 1</div>
<div class="droppable" id="drop2">drop location 2</div>
...
this javascript should work:
$(document).ready(function() {
$(".draggable").draggable({cursor: 'move', helper: 'clone'});
$(".droppable").droppable({
drop: function(event, ui) {
var dragID = ui.draggable.attr('id');
var dropID = event.target.id; // or $(this).attr("id"), or this.id
$.ajax({
type: "POST",
url: 'www.mydomain.com/'+dragID+'/'+dropID,
dataType: 'html',
success: function(){}
});
return false;
}
});
});
ps - you are also doing an ajax POST but with no posted data - I assume that was removed from the question. If you are just hitting the url and passing the 2 id's as shown then a straight GET would suffice.
$.get('www.mydomain.com/'+dragID+'/'+dropID, function(data) {
..
});
The way you are trying to get the id is invalid. You are using the class selector . which will return all objects of the given class. In your example you have 2+ of each class (draggable and droppable).
Secondly, those elements don't have ids so .attr(id) would return null (I think).
Third, you don't have quotes around id which means it would be interpreted as a variable which hasn't been set.
Lastly, to get the id, you can get it using event.target.id in the drop function.
Try the following:
<div class="draggable" id="item1">item 1</div>
<div class="draggable" id="item2">item 2</div>
...
<div class="droppable" id="drop1">drop location 1</div>
<div class="droppable" id="drop2">drop location 2</div>
...
Then:
$(document).ready(function() {
$(".draggable").draggable({cursor: 'move', helper: 'clone'});
$(".droppable").droppable({
drop: function(event, ui) {
var ID1 = event.target.id;
var ID2 = $(this).attr("id");
$.ajax({
type: "POST",
url: 'www.mydomain.com/'+ID1+'/'+ID2,
dataType: 'html',
success: function(){}
});
return false;
}
});
});

How to use flexigrid as a partial view in ASP.NET MVC application?

I am able to display Flexigrid in a normal view called from my main menu. I am using this sample http://mvc4beginner.com/Sample-Code/Insert-Update-Delete/Asp-.Net-MVC-Ajax-Insert-Update-Delete-Using-Flexigrid.html to make it work and it works fine for me.
However, my idea is to use a bit more complex interface - have a regular view with the search controls and on pressing search button show the grid with data for the items I searched.
I tried couple of things so far and can not make it to work. Here is the latest Index view I tried:
#model CardNumbers.Objects.Client
#{
ViewBag.Title = "Clients";
}
<h2>Clients</h2>
<br />
#using (Ajax.BeginForm("Search", "Client",
new AjaxOptions
{
HttpMethod = "POST",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "ClientsResults"
}))
{
<fieldset>
<legend>Search</legend>
<label for="clientNo">Client No: </label>
<input type="number" name="searchClientNo" class="numericOnly" /><br />
<label for="clientName">Client Name: </label>
<input type = "text" size =25 data-autocomplete="#Url.Action("QuickSearch", "Client")" name ="searchClientName" />
<div>
<input type="submit" value="Find / Refresh" />
#*<input type="button" value="Find / Refresh" id="ClientsSearch" data-url="#Url.Action("Client", "Client")" />
#*<input type="submit" value="Find / Refresh" />*#
#* #Ajax.ActionLink("Find / Refresh", "Client", new AjaxOptions {UpdateTargetId = "ClientResults",
InsertionMode = InsertionMode.Replace, HttpMethod = "POST"}) *#
#*}*#
</div>
</fieldset>
<div style="padding-left:150px; padding-top:50px; padding-bottom:50px;" id="ClientsResults">
#*#{Html.RenderPartial("_Client", Model); }*#
#*<table id="flexClients" style="display:none"/>*#
</div>
}
#*<br />*#
You can see all the commented attempts here also. So, the Search method in the Clients controller now has this code:
public ActionResult Search(int? searchClientNo = null, string searchClientName = null)
{
// Assume we want to select everything
var clients = Db.Clients; // Should set type of clients to IQueryable<Clients>
if ((searchClientNo ?? 0) != 0) //Number was supplied
clients = clients.Where(c => (c.Number == searchClientNo));
// If clientNo was supplied, clients is now filtered by that. If not, it still has the full list. The following will further filter it.
if (!String.IsNullOrWhiteSpace(searchClientName)) // Part of the name was supplied
clients = clients.Where(c => (c.Name.Contains(searchClientName)));
return PartialView("_ClientsSearch", clients);
//return PartialView("_Client", clients);
}
The commented view is the partial view which has a flexigrid and it's not working. The _ClientsSearch view is the "normal" index view created by using the template and this works.
Do you see what exactly I am missing? The flexigrid method is simply not firing at all when I attempt to use it as a partial view from that main view.
I haven't figured out the more complex scenario I had originally in mind, but I was able to make it work using the regular view. The helpful idea first came from this FAQ:
http://code.google.com/p/flexigrid/wiki/FAQ and also looking a bit closer to that sample I used.
So, now my Client view is this:
#model CardNumbers.Objects.Client
#{
ViewBag.Title = "Client";
}
<form id="frmClientsSearch">
<label for="clientNo">Client No: </label>
<input type="number" name="searchClientNo" class="numericOnly" /><br />
<label for="clientName">Client Name: </label>
<input type = "text" size =25 value ="Please enter the search value"
name ="searchClientName" />
<input type="button" id="btnClientsSearch" value ="Find / Refresh" />
</form>
<div style="padding-left: 150px; padding-top: 50px; padding-bottom: 50px;" id="ClientsResults">
<table id="flexClients" style="display: none">
</table>
</div>
<div style="display: none">
<form id="sform">
<input type="hidden" id="fntype" name="fntype">
<input type="hidden" id="Id" name="Id">
<label for="Number">Client No: </label>
<input type="number" id="Number" name="Number" class="numericOnly" />
<label for="Name">Client Name: </label>
<input type="text" size="25" id="Name" name="Name" /><br />
<label for="Contact11">Contact 1: </label>
<input type="text" size="25" id="Contact1" name="Contact1" /><br />
<div class="float-right">
<button type="Submit" id="btnSave">Submit</button>
<button type=reset id="btnCancel">Cancel</button>
</div>
</form>
</div>
And the main work is done in the .js file (note the AddFormData method):
/// <reference path = "jquery-1.5.1-vsdoc.js"/>
/// <reference path = "jquery-ui-1.8.11.js"/>
$(document).ready(function() {
$(":input[data-autocomplete]").each(function() {
$(this).autocomplete({ source: $(this).attr("data-autocomplete") });
});
});
$(function () {
$('input[name="delete"]').click(function () {
return confirm('Are you sure?');
});
});
$(".numericOnly").keypress(function (e) {
if (String.fromCharCode(e.keyCode).match(/[^0-9]/g)) return false;
});
$("#flexClients").flexigrid({
url: '/Client/Client/',
dataType: 'json',
colModel: [
{ display: 'Client Id', name: 'Id', width: 100, sortable: true, align: 'center', hide: true},
{ display: 'Client #', name: 'Number', width: 100, sortable: true, align: 'center' },
{ display: 'Name', name: 'Name', width: 350, sortable: true, align: 'center' },
{ display: 'Contact 1', name: 'Contact1', width: 350, sortable: true, align: 'center' },
],
buttons: [
{ name: 'Add', bclass: 'add', onpress: test },
{ name: 'Edit', bclass: 'edit', onpress: test },
{ name: 'Delete', bclass: 'delete', onpress: test },
{ separator: true }
],
searchitems: [
{ display: 'Client Name', name: 'Name' }
],
sortname: "Name",
sortorder: "asc",
usepager: true,
title: 'Clients',
useRp: true,
rp: 15,
showTableToggleBtn: true,
width: 1000,
onSubmit: addFormData,
height: 300
});
//This function adds parameters to the post of flexigrid. You can add a verification as well by return to false if you don't want flexigrid to submit
function addFormData() {
//passing a form object to serializeArray will get the valid data from all the objects, but, if the you pass a non-form object, you have to specify the input elements that the data will come from
var dt = $('#sform').serializeArray();
dt = dt.concat($('#frmClientsSearch').serializeArray());
$("#flexClients").flexOptions({ params: dt });
return true;
}
$('#sform').submit(function () {
$('#flexClients').flexOptions({ newp: 1 }).flexReload();
alert("Hello World");
return false;
});
function test(com, grid) {
if (com === 'Delete') {
var clientName = $('.trSelected td:eq(2)').text();
if (clientName) //Variable is defined and not empty
{
if (confirm("Are you sure you want to delete " + $.trim(clientName) + "?"))
return false;
$('#fntype').val('Delete');
$('#Id').val($('.trSelected td:eq(0)').text());
$('#Number').val('');
$('#Name').val('');
$('#Contact1').val('');
$('.trSelected', grid).each(function () {
var id = $(this).attr('id');
id = id.substring(id.lastIndexOf('row') + 3);
addFormData(); $('#flexClients').flexOptions({ url: '/Client/Client/' }).flexReload();
});
clearForm();
}
} else if (com === 'Add') {
$("#sform").dialog({
autoOpen: false,
show: "blind",
width: 1000,
height: 500
});
$("#sform").dialog("open");
$('#fntype').val('Add');
$('#Number').val('');
$('#Name').val('');
$('#Contact1').val('');
} else if (com === 'Edit') {
$('.trSelected', grid).each(function () {
$("#sform").dialog({
autoOpen: false,
show: "blind",
width: 1000,
height: 500
});
$("#sform").dialog("open");
$('#fntype').val('Edit');
$('#Id').val($('.trSelected td:eq(0)').text());
$('#Number').val($('.trSelected td:eq(1)').text());
$('#Name').val($('.trSelected td:eq(2)').text());
$('#Contact1').val($('.trSelected td:eq(3)').text());
});
}
}
function clearForm() {
$("#sform input").val("");
};
$(function () {
$('#btnSave').click(function () {
addFormData();
$('#flexClients').flexOptions({ url: '/Client/Client/' }).flexReload();
clearForm();
$('#sform').dialog('close');
return false;
});
});
$(function () {
$('#btnCancel').click(function () {
// clearForm();
$('#sform').dialog('close');
return false;
});
});
$(function () {
$('#btnClientsSearch').click(function () {
addFormData();
$('#flexClients').flexOptions({ url: '/Client/Client/' }).flexReload();
//$.ajax({
// url: $(this).data('url'),
// type: 'GET',
// cache: false,
// success: function (result) {
// $('#ClientsResults').html(result);
// }
//});
return;//false;
});
});
And my Client method in the controller is the same as it used to be with minor change.
Now, my next challenge is to generalize the above and also somehow instead of calling the form sForm I showed use a more complex form with validations as I if it is from the Create/Edit view.

Resources