I am using rails3-jquery-autocomplete for autocomplete functionality but when I select through mouse autocomplete works but if I select through keyboard down and arrow and click enter its not working I am having following code. What I am missing
$(".text_field_title").live("focusout",function(){
var name = $(this).attr("name");
var value = $(this).val();
var activity_id = $(this).attr("rel")
var practice_plan_id = $(this).attr('practice_plan_id');
$("#"+activity_id+"_title").bind('railsAutocomplete.select',function(event,data){
var data = [
{
name : name,
value : value
},
{
name : "activity_id",
value : activity_id
},
{
name :"fav_id",
value : data.item.id
}
];
$.ajax({
type: 'POST',
url: 'myurl',
data: data,
dataType: "script"
});
});
});
Related
sorry for the bad title I cannot express the proper subject to my problem
since, I'm a newbie in MVC and ajax I have a problem
In view I prepared a dropdown where it list all the shoes name (Shoe Table), now the customer has to select it but the twist it must display the Shoesprice (Shoe Table) once it select a shoe name. the view code is given below
View:
#Html.DropDownListFor(x => x.shoename, new SelectList(Model.ShoesModel,"shoename","shoename"), "Select Shoes Name", new {id="myDrop",#class="form-control" })
I have the script when you select it the item, this particular syntax is working
Script:
$("#myDrop").change(function ()
{
var value = $(this).val();
console.log(value);
$.ajax({
type: 'POST',
url: '/Customers/GetShoesPrice',
dataType: 'json',
data: { shoesName: $(this).val() },
success: function (data) {
//how can I declare a value to get the and return the price
}
});
}
But, i don't know how to create an ajax syntax (get the price according to shoe name), and set to a controller
thank you for help
Since you want to return single value only, just use data in AJAX success result to show returned price value:
Controller
[HttpPost]
public JsonResult GetShoesPrice(string shoesName)
{
var customerViewPrice = (from c in _SBC.Shoeses // Change the condition here
where c.shoename.Contains(shoesName)
select c.ShoesUnitPrice).FirstOrDefault(); // or SingleOrDefault() for one and only returned value
return Json(customerViewPrice);
}
View (jQuery)
$("#myDrop").change(function () {
var value = $(this).val();
console.log(value);
$.ajax({
type: 'POST',
url: '/Customers/GetShoesPrice',
dataType: 'json',
data: { shoesName: value },
success: function (data) {
// set input element value which will be posted on form submit with DropDownListFor
$('#price').val(data);
}
});
}
Note that if you want to show list of ShoesUnitPrice from selected shoesName, you need to use $.each() loop to iterate returned array of price value.
My application is MVC 5, I use the following Knockout-kendo dropdown list:
<input data-bind="kendoDropDownList: { dataTextField: 'name', dataValueField: 'id', data: foodgroups, value: foodgroup }" />
var ViewModel = function () {
var self = this;
this.foodgroups = ko.observableArray([
{ id: "1", name: "apple" },
{ id: "2", name: "orange" },
{ id: "3", name: "banana" }
]);
var foodgroup =
{
name: self.name,
id: self.id
};
this.foodgroup = ko.observable();
ko.bindingHandlers.kendoDropDownList.options.optionLabel = " - Select -";
this.foodgroup.subscribe(function (newValue) {
newValue = ko.utils.arrayFirst(self.foodgroups(), function (choice) {
return choice.id === newValue;
});
$("#object").html(JSON.stringify(newValue));
alert(newValue.name);
});
};
ko.applyBindings(new ViewModel());
It works great, thanks to this answer Knockout Kendo dropdownlist get text of selected item
However when I changed the observableArray to Ajax:
this.foodgroups = ko.observableArray([]),
$.ajax({
type: "GET",
url: '/Meals/GetFoodGroups',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
self.foodgroups(data);
},
error: function (err) {
alert(err.status + " : " + err.statusText);
}
});
Controller - get the table from ms sql server:
public JsonResult GetFoodGroups()
{
var data = db.FoodGroups.Select(c => new
{
id = c.FoodGroupID,
name = c.FoodGroupName
}).ToList();
return Json(data, JsonRequestBehavior.AllowGet);
}
I get this error when I alert the item name
Unable to get property 'name' of undefined or null reference
What is the difference between hardcoding the array items from using Ajax.
The 'id' field has string datatype in hard coded array.
The 'id' field has number datatype in ajax array.
.
So, the 'id' field has different datatypes in both arrays. However in-condition you have used === operator so it checks value as well as datatype.
For ajax array value is same but its datatype is different so its not returning result.
Let me know if any concern.
I've been doing alot of searching but haven't found a clear answer for this. I have a set up textboxes that and a submit button and a Kendo UI grid. I want to post the data to the grid's datasource so that it will return the results based on the criteria. I am not using the MVC wrappers.
EDIT:
I've gotten closer but I can't seem to get the datasource to send the post data when I click submit. I've debugged and in my $("#fmSearch").submit it is hitting the jquery plugin and I've confirmed that it is converting the form data to JSON properly, but it seems as though it it not sending the updated information to the server so that the Action can read it.
Javascript
var dsGalleryItem = new kendo.data.DataSource({
transport: {
read: {
url: '#Url.Content("~/Intranet/GalleryItem/SearchGalleryItems")',
type: "POST",
data: $("#fmSearch").serializeFormToJSON(),
cache: false
}
},
schema: {
model: {
id: "galleryItemID",
fields: {
galleryItemID: {
nullable: true
},
imageName: {},
collectionName: {},
categoryName: {},
lastUpdatedOn: { type: "date" }
}
}
}
});
var gvResults = $("#gvResults").kendoGrid({
autoBind:false,
columns: [{
field: "imageName",
title: "Item Name",
template: "<a href='#Url.Content("~/Intranet/GalleryItem/Details/")#=galleryItemID#'> #=imageName#</a>"
}, {
field: "collectionName",
title: "Collection"
}, {
field: "categoryName",
title: "Category"
}, {
field: "lastUpdatedOn",
title: "Last Updated",
format: "{0:M/d/yyyy}"
}
],
selectable: "row",
change: onRowSelect,
dataSource: dsGalleryItem
});
$("#fmSearch").submit(
function (event) {
event.preventDefault();
dsGalleryItem.read({ data: $("#fmSearch").serializeFormToJSON() });
});
MVC Action
[HttpPost]
public JsonResult SearchGalleryItems(string keyword, int? category, int? collection, DateTime? startDate, DateTime? endDate)
{
var galleryItemList = (from g in db.GalleryItems
//where g.imageName.Contains(keyword)
select new GalleryItemViewModel
{
galleryItemID = g.galleryItemID,
imageName = g.imageName,
collectionName = g.collection.collectionName,
categoryName = g.category.categoryName,
lastUpdatedOn = g.lastUpdatedOn
});
var galleryItemCount = Json(galleryItemList.ToList());
return Json(galleryItemList.ToList()); ;
}
The action is not setup to retrieve different data right now I just need to know how to connect the form to the grid.
Found the problem. I had this:
dsGalleryItem.read({ data: $("#fmSearch").serializeFormToJSON() });
It needed to be this:
dsGalleryItem.read($("#fmSearch").serializeFormToJSON());
This is my first post. stackoverflow is a wonderful place for developers. Here is my issue.
I am trying to use Autocomplete in JqGrid Edit Form. i successfully retrieved data from server using ajax call but dont know how to display it in the view. below is my code.
FrontEnd Code:
colModel :[
{name:'prf_articlename', index:'prf_articlename', width:90, editable:true, edittype:'text',
editoptions: {
dataInit:function(e){
$(e).autocomplete({
source: function(request, response,term) {
var param = request.term;
$.ajax({
url: '/Myelclass/AutoCompleteServlet.do?term='+param+"&action="+"artname",
success: function (data) {
response($.map(data, function(item) {
return {
label: item.label,
};
}));//END Success
},
});//END AJAX
},
minLength: 2,
});//END AUOTOCOMPLETE
}//END Dataint
}//END Dataint
},
BackEnd Code:
String term = request.getParameter("term");
List<AutoComplete> articlelist = prfbo.getArticleNameinEditGrid(term);
System.out.println("List Value " +articlelist.size());
JSONArray jsonOrdertanArray = JSONArray.fromObject(articlelist);
System.out.println(jsonOrdertanArray);
out.println(jsonOrdertanArray);
Any one help on this???
This is what I personally use in my project:
Inside colModel:
dataInit: function (elem) { NameSearch(elem) }},
The function:
function NameSearch(elem) {
$(elem).autocomplete({ source: '/Controller/NameSearch',
minLength: 2, autosearch: true,
select: function (event, ui) {
$(elem).val(ui.item.value);
$(elem).focus().trigger({ type: 'keypress', charCode: 13 });
}
})//$(elem).autocomplete
$(elem).keypress(function (e) {
if (!e) e = window.event;
if (e.keyCode == '13') {
setTimeout(function () { $(elem).autocomplete('close'); }, 500);
return false;
}
})//$(elem).keypress(function (e){
} //function NameSearch(elem) {
I'm also dealing with an Enter key press as well in the above function.
here is the complete code for my Autocomplete in jqgrid Edit form..
colModel :[
{name:'name', index:'name', width:90, align:'center', editable:true, hidden: false, edittype:'text',
editoptions:{
dataInit:function (elem) {
$(elem).autocomplete({
minLength: 2,
source: function(request, response,term) {
var param = request.term; //values we enter to filter autocomplete
$.ajax({
url: "myurl",
dataType: "json",
type:"GET",
success: function (data) {
response($.map(data, function(item) {
return {
//can add number of attributes here
id: item.id,
shform: item.shortform,
value: item.name,
clr : item.color, //here apart from name and id i am adding other values too
size: item.size,
remar:item.remarks,
subs: item.subs,
selec:item.selec ,
};
}));//END Response
},//END Success
});//END AJAX
},
select: function( event, ui ) {
// setting values to textbox in jqgrid edit form based on selected values
$('#textbox1').val(ui.item.id);
$('#textbox2').val(ui.item.shform);
$('#textbox3').val(ui.item.clr);
$('#textbox4').val(ui.item.size);
$('#textbox5').val(ui.item.sizeremar);
$('#textbox6').val(ui.item.subs);
$('#textbox7').val(ui.item.selec);
$('#textbox8').val(ui.item.selp);
}
});
$('.ui-autocomplete').css('zIndex',1000); // if autocomplete has misalignment so we are manually setting it
}
}, editrules :{required : true},
formoptions:{rowpos: 1, colpos: 2}
},
........
]
server code :
String term = request.getParameter("term");
List<ArticleDetails> articlelist = prfbo.getPrfArticleName(term); //DB call via BO and DAO class
System.out.println("List Value " +articlelist.size());
JSONArray jsonOrdertanArray = JSONArray.fromObject(articlelist);
System.out.println(jsonOrdertanArray);
out.println(jsonOrdertanArray);
hope some one find it useful.
I'm currently working in ASP.NET MVC 4 and I'm trying to do something special here.
Here's the code I currently have for my dropdownlist:
#Html.DropDownListFor(m => m.SourceList, new SelectList(Model.SourceList, "Id", "Name", new { id = "SourceList" }))
Now this works, but it's pretty dumb what I'm doing here. In my back-end I query again to get the entire model from the id I just selected.
What I need is not the Id of the selected model, but the entire model. Is there any way of doing this?
My current JQuery callback:
$.ajax({
url: '#Url.Action("SetLicensesAfterSourceChange", "Permission")',
type: 'POST',
dataType: 'json',
contentType: 'application/json;',
data: JSON.stringify({ "Id" : selectedStartSourceId, "sourceList" : jsonSourceList }),
success: function (result) {
//Do stuff here
}
});
What I want to be able to do:
$.ajax({
url: '#Url.Action("SetLicensesAfterSourceChange", "Permission")',
type: 'POST',
dataType: 'json',
contentType: 'application/json;',
data: "selectedModel" = modelFromDropDownList,
success: function (result) {
//Do stuff here
}
});
It's probably a bit far-fetched, but you could create a Javascript array representation of your entire list of source objects, and use jQuery and a simple html select ( with the id & name for the options) to retrieve the item from the array.
<script>
var items = [
{
name = "een",
value = "1",
propertyX = "hallo"
},
{
name = "twee",
value = "2",
propertyX = "wereld"
}
];
$("#ddlselect").change(function(e) {
e.preventDefault();
var selectedOptionVal = $(this).val();
var found = null;
foreach (item in items)
{
if (!found && item.value == selectedOptionVal)
found = item;
}
// use found if set
if (found)
{
}
});
</script>
<select id="ddlselect">
<option value="">-- kies --</option>
<option value="1">een</option>
<option value="2">twee</option>
</select>