jquery autocomplete - selected value disappears from textbox - javascript

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);
}
});

Related

Dynamic search bar - Adding element from drop down in ASP.NET MVC5

I'm programming in ASP.NET MVC5. On one of my views I need to be able to create a search bar. For this example, lets say you are searching for names. When you start typing a person's name, all of the results will be displayed in a drop down list as you type.
Here is the tricky part that I need help with. I want there to be a button for each entry in the drop down list to "Add" that person name to a table.
For example, I'm looking for the name "Debo" As I type "D-E-B", I see the name I want in the drop down list. I click "Add" and it removes the name "Debo" from the drop down list and adds it to my table. Once "Debo" has been added to the table, I need to be able to see Debo's age and gender that I wouldn't see in the drop down list.
I don't have any code examples because I'm not even sure where to start. I've researched this like crazy, but I cannot find anything. Any help or pointing me in the right direction, will be greatly appreciated,
I am using autocomplete by JQueryUI.
Please refer below code hopefully it will helps you.
JavaScript Code:
$("#member_CompanyName").autocomplete({
highlightClass: "bold-text",
search: function () {
$(this).addClass('working');
},
source: function (request, response) {
var companyDetails = new Array();
$.ajax({
url: "/ControllerName/JsonActionResult",
async: false,
data: {
"parm": request.term
},
success: function (data) {
if (data.length === 0) {
companyDetails[0] = {
label: "No Result Found",
Id: ""
};
} else {
for (var i = 0; i < data.length; i++) {
companyDetails[i] = {
label: data[i].Value,
Id: data[i].Key
};
$("#no-companyfound").css("display", "none");
}
}
}
});
response(companyDetails);
},
minLength: 2,
select: function (event, ui) {
/*Select Function works on when you selects element from Response List*/
$.ajax({
async: false,
url: "/ControllerName/JsonActionResultonClick",
data: {
"id": ui.item.Id
},
success: function (data) {
// Do your success logic here
},
error: function (xhr, ajaxOptions, thrownError) {
// Error Logic here
}
});
},
open: function () {
$(this).removeClass("ui-corner-all").addClass("ui-corner-top");
},
close: function () {
$(this).removeClass("ui-corner-top").addClass("ui-corner-all");
}
});
Controller Code:
[HttpGet]
public JsonResult JsonActionResult(string parm) {
// Replace your special Character like "-,~" etc from your search string
var result = new List < KeyValuePair < string,
string >> ();
foreach(var item in _obj_fulldetails.GetCompanylistSearch(parm)) {
result.Add(new KeyValuePair < string, string > (item.Value.ToString(), item.Text));
}
return Json(result, JsonRequestBehavior.AllowGet);
}
You can implement "Add"
button your logic on Item select. If you still want add button you can edit response string into JS.
See my response screenshot :

jQuery UI Autocomplete - Trigger an event without select

I have this autocomplete in a input box and all is working fine:
$(function() {
$("#customer").autocomplete({
minLength: 1,
source: function(request, response) {
$.getJSON('url.php', { 'string': request.term }, function(data) {
if(data) {
var clienti = data.error ? [] : $.map(data, function(customer) {
return {
label: customer.fullname,
array: customer
};
});
response(clienti);
}
});
},
select: function( event, ui ) {
$("#description").val(ui.item.array.description);
}
})
});
I want to call (trigger) the same autocomplete function ON LOADING another page, but WITHOUT select an item! (simply by pass data to Ajax).
If i use $("#customer").autocomplete("search") all is working BUT i need to select the ITEM to view the $("#description").val !
$("#customer").val is loaded by PHP on page load.
How could i do?
Thank you.

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();}
}

Jquery autocomplete on select event

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 );
}

Categories

Resources