Jquery autocomplete on select event - javascript

I am using jQuery autocomplete and its working fine, now I want to store a variable in session from jQuery when following condition occurs.
When someone types any word jQuery shows suggestion dropdown, if someone select an item from that suggestion dropdown.
I want to capture above point and store a variable in session.
I searched Google, StackOverflow but find no relevant solution. My code for autocomplete is following:
$(".autosearch-smart").autocomplete('Home/GetCompanyNames', {
minChars: 1,
width: 402,
matchContains: "word",
autoFill: true
});
and this is what I tried to do:
$(".autosearch-smart").autocomplete('Home/GetCompanyNames', {
minChars: 1,
width: 402,
matchContains: "word",
autoFill: true,
select: function (a, b) {
alert("selected");
}
});
EDIT : Select event handler is also not working
I am using asp.net MVC3 with C#. Please help me out and thanks in advance.

So if I understand correctly you want to store the selected value in a variable sessions
you can get the value out of the selected item through following code:
$(".autosearch-smart").autocomplete('Home/GetCompanyNames', {
minChars: 1,
width: 402,
matchContains: "word",
autoFill: true,
select: function (event, ui) {
var label = ui.item.label;
var value = ui.item.value;
//store in session
document.valueSelectedForAutocomplete = value
}
});
the value and label are json objects that came from the server
Hope this helps

Well, if you want to store in session using asp.net mvc3 then do the following
$(".autosearch-smart").autocomplete('Home/GetCompanyNames', {
minChars: 1,
width: 402,
matchContains: "word",
autoFill: true,
select: function (event, ui) { //must be cleared with function parameter
//alert(ui.item.label); //will show you the selected item
$.ajax({
type: 'POST',
url: '/Controller/Action1', //whatever any url
data: {label: ui.item.label},
success: function(message) { if(message.data == true) ... else ... },
dataType: 'json'
});
}
});
and controller
[HttpPost]
public JsonResult Action1( string label ) {
this.Session["AnyValue"] = label;
return Json( new {
data = true
}, JsonRequestBehavior.AllowGet );
}

Related

i dont want select2 multi select drop down loose data in page refresh. select2 drop down should maintain state

I don't want select2 multi select drop down loose data in page refresh. select2 drop down should maintain state
below is my code. its working fine, I have only problem that select2 is losing selection/data if we refresh the page.My requirement is even after page refresh it should not remove there values/or empty.
$processOrderNbr.select2({
ajax: getProcessOrderNbr(),
minimumInputLength: 4,
placeholder: " ",
allowClear: false,
multiple: true
});
function getProcessOrderNbr() {
return {
url: 'GetProcessOrder',
dataType: 'json',
delay: 250,
data: function (params) {
return {
searchKeyword: params
};
},
results: function (data) {
return {
results: $.map(data, function (item) {
return {
text: item,
id: item
}
})
};
}
};
}
You need to put them again into the select2 boxes.
I had a similar issue, where I work with window.sessionStorage to store the selected values. After reloading the page, I set the values stored in the session storage into the select2 boxes with this code:
var selectionList = [{ id: window.sessionStorage.getItem("searchValue"), text: window.sessionStorage.getItem("searchValue")}];
$("#searchValue").select2({
data: selectionList
});
$('#searchValue').val(window.sessionStorage.getItem("searchValue")).trigger("change");
To store the values in the window.sessionStorage you can use this code:
$('#searchValue').select2({
...
.on("change", function (e) {
window.sessionStorage.setItem("searchValue", $(this).val());
}
...
Maybe this solution helps you in your case, but someone knows a better solution?
If you need to show the previous wrote value after reloading the page without losing the data that is the solution.
var dataCategory = JSON.parse(sessionStorage.getItem('category'));
var select = $("#category");
select.select2({
tags: true,
allowClear: true,
maximumInputLength: 30,
maximumSelectionLength: 20,
tokenSeparators: [',', ' '],
data: dataCategory
}).on("change", function (e) {
var selected = []; // create an array to hold all currently wrote by user
// loop through each option
$('#category option').each(function() {
// if it's selected, add it to the array above
if (this.selected) {
selected.push(this.value);
}
});
// store the array of selected options
sessionStorage.setItem('category', JSON.stringify(selected));
});
// set and show the previous wrote keywords
var dataCategoryLength = dataCategory.length;
for (var i =0; i < dataCategoryLength; i++) {
$('#category').val(dataCategory).trigger('change');
}

dropdown not being populated in filter toolbar in jquery grid

I have referred this link and also this one link Both are Oleg's solutions to the problem. I used the same solution but the drop down doesn't populate with the values except for 'All'
I placed the code in load complete and I see the values when you call the 'setSearchSelect' function but only 'All' shows up in the dropdown.
Here's the code-
setupGrid: function (grid, pager) {
$(grid).jqGrid({
datatype: 'local', // set datatype to local to not inital load data
mtype: 'GET',
url: swUrl + ptSearchDashboardUrl,
colNames: colNames,
colModel: colModel,
altRows: false,
pager: $(pager),
loadonce: true,
sortable: true,
multiselect: true,
viewrecords: true,
loadComplete: function (data) {
//setSearchSelect.call($grid, 'RequestType');
//setSearchSelect.call($grid, 'Country');
},
onSelectRow: function() {
var checkedIDs = $(this).jqGrid('getGridParam', 'selarrrow');
if (checkedIDs.length > 0)
$("#ReassignBtn").show();
else
$("#ReassignBtn").hide();
}
}).navGrid(pager, { add: false, edit: false, del: false }).trigger('reloadGrid', [{ current: true }]);
setSearchSelect.call($grid, 'RequestType');
setSearchSelect.call($grid, 'Country');
$grid.jqGrid("setColProp", "Name", {
searchoptions: {
sopt: ["cn"],
dataInit: function(elem) {
$(elem).autocomplete({
source: getUniqueNames.call($(this), "Name"),
delay: 0,
minLength: 0,
select: function(event, ui) {
var $myGrid, grid;
$(elem).val(ui.item.value);
if (typeof elem.id === "string" && elem.id.substr(0, 3) === "gs_") {
$myGrid = $(elem).closest("div.ui-jqgrid-hdiv").next("div.ui-jqgrid-bdiv").find("table.ui-jqgrid-btable").first();
if ($myGrid.length > 0) {
grid = $myGrid[0];
if ($.isFunction(grid.triggerToolbar)) {
grid.triggerToolbar();
}
}
} else {
// to refresh the filter
$(elem).trigger("change");
}
}
});
}
}
});
$(grid).jqGrid('filterToolbar', {stringResult:true, searchOnEnter:true, defaultSearch:"cn"});
}
This is from the UI - I can only see one option value even though there are many.
<td class="ui-search-input">
<select name="RequestType" id="gs_RequestType" style="width: 100%;">
<option value="">All</option>
</select>
</td>
The code which you use getUniqueNames which uses .jqGrid("getCol", columnName) to get the data from the column. On the other side you use datatype: 'local' to create empty grid. The calls setSearchSelect.call($grid, 'RequestType');, setSearchSelect.call($grid, 'Country'); and getUniqueNames.call($(this), "Name") will be made before the grid will be filled with data. Thus you fill set empty set of select elements.
I suppose that you change later the datatype to "json" or "xml" and reload the grid. Only after your get response from the server you will ba able to fill the select values. I would suggest you to use beforeProcessing, which will be called after loading the data from the server, but before processing of the data. You can modify getUniqueNames and setSearchSelect so that it get the data from the input data directly and calls setColProp. Finally you should call destroyFilterToolbar and call filterToolbar once more to create the filter toolbar with the current data.

jquery autocomplete - selected value disappears from textbox

I have written a custom jquery autocomplete function to display certain values and textfields to update on selecting the value as per the code below:
<input type="text" name="promoitem" id="promoitem">
$('#promoitem').autocomplete({
source: "BckProcesses/GetPromoItems.asp",
create: function() {
$(this).data('ui-autocomplete')._renderItem = function(ul, item) {
return $('<li>')
.append('<a>' + item.promodesc + '</a>')
.appendTo(ul);
}
},
select: function(event, ui) {
$('#promoitem').val(ui.item.promodesc);
$('#promocost').val(ui.item.promocost);
$('#promoqty').val(ui.item.qty);
$('#hidden_promo_item_id').val(ui.item.id);
}
});
This is what is return by the source file (GetPromoItems.asp)
[{"id": "1", "promodesc": "Ipad 4 ", "promocost": "200", "qty": "1"},{"id": "2", "promodesc": "Village Tickets", "promocost": "20", "qty": "2"}]
However, when I select the value from the ul, everything gets populated except the promoitem textfield. That fields goes to being blank.
Can anyone please let me know what could be causing this?
Thanks
Sam
Since you're providing your own logic in the select handler, you need to prevent the default action, which is to place ui.item.value in the input.
Right now, your code is running, and then jQueryUI is immediately trying to place ui.item.value in the input, which explains the empty value.
So really all you need to do is call event.preventDefault(); or return false; from the select handler:
select: function(event, ui) {
$('#promoitem').val(ui.item.promodesc);
$('#promocost').val(ui.item.promocost);
$('#promoqty').val(ui.item.qty);
$('#hidden_promo_item_id').val(ui.item.id);
event.preventDefault(); // <---
}
After spending an hour, finally got to an point that Jquery UI autocomplete sets the value to default.
Only one line needs to put and prevent Jquery default function to get the wok done.
// pincode list autocomplete
$('input[name=\'pincode\']').autocomplete({
'source': function (request, response) {
$.ajax({
url: 'index.php?route=seller/pincode/pincodeAutocomplete&filter_name=' + encodeURIComponent($('input[name=\'pincode\']').val()),
dataType: 'json',
success: function (json) {
json.unshift({
pincode_id: '',
pincode: '-- None --'
});
response($.map(json, function (item) {
return {
label: item['pincode'],
value: item['pincode_id']
}
}));
}
});
},
'select': function (event, ui) {
event.preventDefault();
$('input[name=\'pincode\']').val(ui.item.label);
$('input[name=\'pincode_id\']').val(ui.item.value);
}
});

How to manually set the value (and trigger the select event) to jQuery autocomplete

I know there are a few questions about this, but I couldn't find anyone that sets the value and also triggers the select function.
My code is:
$("#ux-selfservice-account-edit-nationality").autocomplete({
source: countryList,
minLength: 1,
autoFocus: true,
select: function(event, ui) {
$(this).val(ui.item.label).attr("oid", ui.item.oid);
var select = $(this).closest(".ux-selfservice-account-box-edit").find(".ux-selfservice-account-edit-dni-type");
// Check if the user has selected a different country (against the site)
if (ui.item.iataCode == options.countryCode) {
$(select).find("option").show();
}
else {
$(select).find("option:not([value='PAS']):not([value=''])").hide();
if ($(select).val() != "PAS") $(select).val('');
}
return false;
},
focus: function(event, ui) {
return false;
},
search: function(event, ui) {
$(this).attr("oid", "0");
}
});
The countries list is something like this:
[
{
iataCode: "AR",
label: "Argentina",
value: "Argentina",
oid: 28515
},
....
]
As you can see I have a very small check in the select function, if the user selects a different country I hide or show some options from another select drop down.
Now my problem is that sometimes I want the country to be set by javascript, so that the user sees the country name in the field, the oid is set to the attr and also checks the country.
Now I am doing something like this..
$("#ux-selfservice-account-edit-nationality").val(getCountryName(profile.personalInfo.country)).attr("oid", profile.personalInfo.country);
But of course this is wrong and doesn't check the other validation. also I can't do the validation here because I don't have the countryCode (iataCode). I know I can find it in the list, but the point is to use the same function of the autocomplete..
Why don't you extract the logic in the select event handler to a separated function that you can call elsewhere from your Javascript code?
All you need in that function is the country input (which is this in your current code, and the selected country json, which is the ui.item);
So you could extract your current logic into a new function countrySelected:
var countrySelected = function (countryInput, countryJSON) {
$(countryInput).val(countryJSON.label).attr("oid", countryJSON.oid);
var select = $(countryInput).closest(".ux-selfservice-account-box-edit").find(".ux-selfservice-account-edit-dni-type");
// Check if the user has selected a different country (against the site)
if (countryJSON.iataCode == options.countryCode) {
$(select).find("option").show();
} else {
$(select).find("option:not([value='PAS']):not([value=''])").hide();
if ($(select).val() != "PAS") $(select).val('');
}
}
Then update your autocomplete declaration so the select event handler uses this function:
$("#country").autocomplete({
minLength: 1,
source: countries,
autoFocus: true,
select: function (event, ui) {
//just call the new function
countrySelected(this, ui.item);
return false;
},
focus: function (event, ui) {
return false;
},
search: function (event, ui) {
$(this).attr("oid", "0");
}
});
This way you can also manually call the countrySelected function:
var countries = [{
iataCode: "AR",
label: "Argentina",
value: "Argentina",
oid: 28515
},
...
];
countrySelected($("#country"), countries[0]);
I have created this fiddle where you can see it in action.

How do I create a delete button on every row in slickgrid with confirmation?

As the title said it, how do I do it?, I am using this button created by jiri:
How do i create a delete button on every row using the SlickGrid plugin?
when I add an if(confirmation(msg)) inside the function it repeats me the msg ALOT
maybe its because i refresh-ajax the table with each modification.
ask me if you need more info, I am still noob here in stackoverflow :P
(also if there is someway to "kill" the function)
here is the button, iam using(link) i added the idBorrada to check whetever the id was already deleted and dont try to delete it twice, also here is a confirm, but when i touch cancel it asks me again.
$('.del').live('click', function(){
var me = $(this), id = me.attr('id');
//assuming you have used a dataView to create your grid
//also assuming that its variable name is called 'dataView'
//use the following code to get the item to be deleted from it
if(idBorrada != id && confirm("¿Seguro desea eleminarlo?")){
dataView.deleteItem(id);
Wicket.Ajax.ajax({"u":"${url}","c":"${gridId}","ep":{'borrar':JSON.stringify(id, null, 2)}});
//This is possible because in the formatter we have assigned the row id itself as the button id;
//now assuming your grid is called 'grid'
//TODO
grid.invalidate();
idBorrada= id;
}
else{
};
});
and i call the entire function again.
hope that help, sorry for the grammar its not my native language
Follow these steps,
Add a delete link for each row with of the columns object as follows,
var columns =
{ id: "Type", name: "Application Type", field: "ApplicationType", width: 100, cssClass: "cell-title", editor: Slick.Editors.Text, validator: requiredFieldValidator, sortable: true },
{ id: "delete", name: "Action", width: 40, cssClass: "cell-title", formatter: Slick.Formatters.Link }
];
Add a Link Formatter inside slick.formatters.js as follows,
"Formatters": {
"PercentComplete": PercentCompleteFormatter,
"YesNo": YesNoFormatter,
"Link": LinkFormatter
}
function LinkFormatter(row, cell, value, columnDef, dataContext) {
return "<a style='color:#4996D0; text-decoration:none;cursor:pointer' onclick='DeleteData(" + dataContext.Id + ", " + row + ")'>Delete</a>";
}
Add the following delete function in javascript
function DeleteData(id, rowId) {
var result = confirm("Are you sure you want to permenantly delete this record!");
if (result == true) {
if (id) {
$.ajax({
type: "POST",
url: "DeleteURL",
data: { id: id },
dataType: "text",
success: function () {
},
error: function () {
}
});
}
dataView.deleteItem(id);
dataView.refresh();}
}

Categories

Resources