I have a scenario as follows,
Need to put autocomplete functionality on dynamic textbox with onkeyup functionality
My code is as follows, Here i have invoked a function "GetName" on buttonclick where am loadin the dynamic textboxes
function GetName() {
var dataToSend = JSON.stringify({ prefixText: $('#search').val(), Id: $("#SearchType").val()
});
$.ajax({
type: "POST",
data: { jsonData: dataToSend },
url: "GetName",
datatype: "json",
success: function (result) {
$("#ResourceNames").empty();
$("#ResourceNames").append('<table>');
$.each(result, function (i, Name) {
$("#ResourceNames").append('<tr><td ><Label>' + Name.Value + '</label></td><td> <input type="text" id="Supervisor" class = "form-control", onkeyup="GetResource(\'' + Name.Text + '\');"/></td></tr>');
});
},
error: function (xhr, status) {
alert(status);
}
})
$("#ResourceNames").append('</table>');
}
Here onkeyup event of textbox supervisor am calling the below function getresource with an argument
function GetResource(i) {
debugger;
var dataToSend = JSON.stringify({ prefixText: $("#Supervisor").val(), designation: i });
$.ajax({
url: "GetSupervisor",
data: { jsonData: dataToSend },
dataType: 'json',
type: 'POST',
success: function (data) {
$("#Supervisor").autocomplete({source:data});
});
},
error: function (error) {
alert('error; ' + error.text);
}
});
}
am not able to bind autocomplete data to dynamic textbox, can anyone help me out on the same?
You have several issues in your code:
First of all jQuery doesn't concatenates strings into DOM, it creates a DOMElement. So,
$("#ResourceNames").append('<table>'); will append an entire <table> element. Anything you append to #ResourceNames will be added after the table, not inside it.
The HTML you're appending contains id. So there can be multiple elements with same id which is invalid, depending on the response. It's better to use a common classname for those elements instead.
You don't need to manually handle the keyup event. You can specify the url you want to hit as the value of the source option of autocomplete, provided it returns a response suitable for the autocomplete. see this example in docs.
Instead of passing the value via the inline handler, you can store the value as a data-* attribute and access it later.
So your code should be something along:
function GetName() {
var dataToSend = JSON.stringify({ prefixText: $('#search').val(), Id: $("#SearchType").val()});
$.ajax({
type: "POST",
data: { jsonData: dataToSend },
url: "GetName",
datatype: "json",
success: function (result) {
var htmlString ="<table>";
$.each(result, function (i, Name) {
htmlString +="<tr><td ><Label>" + Name.Value + "</label></td><td> <input type='text' class = 'form-control Supervisor' data-name='"+ Name.Text + "'/></td></tr>";
});
},
error: function (xhr, status) {
alert(status);
}
})
$("#ResourceNames").append(htmlString);
$(".Supervisor")..autocomplete({
source: "GetSupervisor" // where GetSupervisor is your data source
});
}
If you want to manually send requests along with data and pass the results into the autocomplete, you can specify an function as the value of source option. (See my another answer for more info). for example:
$(".Supervisor").autocomplete({
source: function(request,response){
/*send the request here.
request.term contains the current value entered in textfield
pass the results you want to display like response(data)*/
}
});
Read the API documentation, play with it for a while and you'll be able to get it working.
Related
I have a few checkboxes on my page. I have some jquery in place to ensure that only one checkbox is checked at a time. I have assigned a specific value to each checkbox. The below ajax finds the checkbox that is checked and I'm grabbing the value associated to it. How do I pass that value to my action?
AJAX
$("input:checkbox").click(function () {
var PaymentID = document.querySelector('#chkBox:checked').value;
alert(PaymentID); // for test
$.ajax({
type: "POST",
dataType: "json",
data: PaymentID,
contentType: "application/json; charset=utf-8",
url: "#Url.Action("MyAction", "Home")",
success: function () {
return PaymentID; // Failed attempt at passing data.
}
})
})
Action:
[HttpPost]
public ActionResult MyAction(string PaymentID)
{
// Magic
}
Please keep in mind i am fairly new to ajax. Thx guys.
You can pass a javascript object with name PaymentID ( same name as your action method parameter)
data: { PaymentID: PaymentID },
You do not need to specify contentType as you are sending a simply object. Also you do not necessarily need to specify dataType for your ajax call to send the data.
This should work.
var PaymentID = "some value";
$.ajax({
type: "POST",
data: { PaymentID: PaymentID },
url: "#Url.Action("MyAction", "Home")",
success: function (response) {
console.log('response', response);
}
});
Or you can use the $.post method.
$.post("#Url.Action("MyAction", "Home")",{ PaymentID: PaymentID }, function(response) {
console.log('response', response);
});
I am passing an object to my controller like so:
var form = JSON.stringify({
"subRevisedRequest": $('#frmRevised').val(),
"subSubcontractor": $('#frmSubcontractor').val(),
"subDescription": $('#frmDesc').val(),
"subCostCode": $('#frmCostCode').val(),
"subAmt": $('#frmAmt').val(),
"subPaymentTerms": "terms",
"subRetainage": 10,
"subComments": $('#frmComment').val()
});
$.ajax({
url: '#Url.Action("CreateSubcontracts", "Routing")',
type: "POST",
datatype: "JSON",
contentType: "application/json; charset=utf-8",
data: form,
success: function(result) {
if (!result.success) {
$('#errormsg').empty();
$('#errormsg').append(result.message);
} else {
location.href = '#Url.Action("Index", "Home")';
}
},
error: function (result) {
alert("Failed");
}
});
my controller sees this as the object it is looking for:
public ActionResult CreateSubcontracts(RoutingSubcontracts s)
My problem is that I'd like to pass along just one more string. I know I can make a view specific model but I was wondering if I could do something like this for example:
public ActionResult CreateSubcontracts(RoutingSubcontracts s, string bu)
I have tried the the following with no luck:
data: JSON.stringify({ "s": form, "bu": "251" }),
but the complex object just comes through as null. Is there a way I can pass the object and a string through as well?
Try adding the string item in the JSON you already have. Dont stringify it or it will just send a big string that youll have to parse again on the server.
var form = {
"subRevisedRequest": $('#frmRevised').val(),
"subSubcontractor": $('#frmSubcontractor').val(),
"subDescription": $('#frmDesc').val(),
"subCostCode": $('#frmCostCode').val(),
"subAmt": $('#frmAmt').val(),
"subPaymentTerms": "terms",
"subRetainage": 10,
"subComments": $('#frmComment').val(),
"bu": "251" // add it here
};
$.ajax({
url: '#Url.Action("CreateSubcontracts", "Routing")',
type: "POST",
datatype: "JSON",
data: form,
success: function(result) {
if (!result.success) {
$('#errormsg').empty();
$('#errormsg').append(result.message);
} else {
location.href = '#Url.Action("Index", "Home")';
}
},
error: function (result) {
alert("Failed");
}
});
In your view jquery create a second var for bu. Assign the data in you ajax call like this;
data: { "s" : form, "bu" : "251" }
In your controller method change the signature to include a default value for bu like this;
public ActionResult CreateSubcontracts(RoutingSubcontracts s, string bu = "NoValue")
With the default value set bu will act like an optional parameter
I have this ajax code:
return $.ajax({
type: "POST",
url: "somefile.php",
cache:false,
data: { "yfilter": $("#yearFilter").serializeArray(),
"gfilter": $("#genreFilter").serializeArray() },
dataType:"json",
success: function(data){
alert("success");
}
This works fine, but I need to pass the data parameter dynamically. For now I need the above data parameter content and a single string.
How do I pass this dynamically? / How do I store it in a variable and pass it to the "data:" field?
{ "yfilter": $("#yearFilter").serializeArray(),
"gfilter": $("#genreFilter").serializeArray() }
I tried JSON.stringify I I couldn't get it to work probably due to the data being an array.
The year and genre arrays are coming directly from the jquery drop down menu. It is selected like by it's #id like so "$("#yearFilter")". This is the select form element.
<select multiple="multiple" name="yearFilter[]" class="filterChange" id="yearFilter">
What I need at the base level is:
var someData = "";
if(...){
someData = { "yfilter": $("#yearFilter").serializeArray(),
"gfilter": $("#genreFilter").serializeArray() };
}
else if(...){
someData = "sampleString";
}
And in ajax call:
...
data: someData,
...
I think I have an idea what you want but post has been overly complicated by extraneous issues like json stringify . Here's a function that could be used in several places eleswhere in your code to make one type of AJAX call or another.
You would then perhaps have several buttons and call the function within handlers for each type of button and change the argument passed to function
doAjax('someval');/* use in button 1*/
doAjax('someOtherval');/* use in button 2*/
function doAjax(arg) {
var someData = "";
if (arg == 'someval') {
someData = {
"yfilter": $("#yearFilter").val(),
"gfilter": $("#genreFilter").val()
};
} else {
someData = "sampleString";
}
$.ajax({
type: "POST",
url: "somefile.php",
cache: false,
data: someData,
dataType: "json",
success: function(data) {
if (arg == 'someval') {
alert("success 1");
} else {
alert("success 2");
}
}
})
}
Hope I've understood what you're asking for.
You could do something like this:
var parameters = {};
if (...) {
parameters = $("#yearFilter").serializeArray();
}
if () {
parameters = $("#genreFilter").serializeArray();
}
and then replace the line:
parameters: { "yfilter": $("#yearFilter").serializeArray(),
"gfilter": $("#genreFilter").serializeArray() },
with:
data: parameters,
JSON type should be best option for dynamically data. push whatever data you wish to inside json like shown below, Hence create your json dynamically and send as ajax data.
var employees = {
accounting: [],
dept: "HR"
};
employees.accounting.push({
"firstName" : item.firstName,
"lastName" : item.lastName,
"age" : item.age
});
$.ajax({
url: POSTURL,
type: 'POST',
dataType: 'json',
data : employees,
contentType: 'application/json; charset=utf-8',
success: function (results)
{
},
error: function (results)
{
jQuery.error(String.format("Status Code: {0}, ", results.status, results.statusText));
}
});
Try it:
someData = JSON.stringify({ yfilter: $("#yearFilter").val(), gfilter: $("#genreFilter").val() });
It will work.
I am using ASP.NET MVC3 with EF Code First. I have not worked previously with jQuery. I would like to add autocomplete capability to a dropdownlist that is bound to my model. The dropdownlist stores the ID, and displays the value.
So, how do I wire up the jQuery UI auto complete widget to display the value as the user is typing but store the ID?
I will need multiple auto complete dropdowns in one view too.
I saw this plugin: http://harvesthq.github.com/chosen/ but I am not sure I want to add more "stuff" to my project. Is there a way to do this with jQuery UI?
Update
I just posted a sample project showcasing the jQueryUI autocomplete on a textbox at GitHub
https://github.com/alfalfastrange/jQueryAutocompleteSample
I use it with regular MVC TextBox like
#Html.TextBoxFor(model => model.MainBranch, new {id = "SearchField", #class = "ui-widget TextField_220" })
Here's a clip of my Ajax call
It initially checks its internal cached for the item being searched for, if not found it fires off the Ajax request to my controller action to retrieve matching records
$("#SearchField").autocomplete({
source: function (request, response) {
var term = request.term;
if (term in entityCache) {
response(entityCache[term]);
return;
}
if (entitiesXhr != null) {
entitiesXhr.abort();
}
$.ajax({
url: actionUrl,
data: request,
type: "GET",
contentType: "application/json; charset=utf-8",
timeout: 10000,
dataType: "json",
success: function (data) {
entityCache[term] = term;
response($.map(data, function (item) {
return { label: item.SchoolName, value: item.EntityName, id: item.EntityID, code: item.EntityCode };
}));
}
});
},
minLength: 3,
select: function (event, result) {
var id = result.item.id;
var code = result.item.code;
getEntityXhr(id, code);
}
});
This isn't all the code but you should be able to see here how the cache is search, and then the Ajax call is made, and then what is done with the response. I have a select section so I can do something with the selected value
This is what I did FWIW.
$(document).ready(function () {
$('#CustomerByName').autocomplete(
{
source: function (request, response) {
$.ajax(
{
url: "/Cases/FindByName", type: "GET", dataType: "json",
data: { searchText: request.term, maxResults: 10 },
contentType: "application/json; charset=utf-8",
success: function (data) {
response($.map(data, function (item) {
return {
label: item.CustomerName,
value: item.CustomerName,
id: item.CustomerID
}
})
);
},
});
},
select: function (event, ui) {
$('#CustomerID').val(ui.item.id);
},
minLength: 1
});
});
Works great!
I have seen this issue many times. You can see some of my code that works this out at cascading dropdown loses select items after post
also this link maybe helpful - http://geekswithblogs.net/ranganh/archive/2011/06/14/cascading-dropdownlist-in-asp.net-mvc-3-using-jquery.aspx
What i am trying to do is get a user to change one drop down, which then calls an ajax function which posts to the code behind (vb.net file) then clears and populates another asp dropdown list with the data returned from the function..hope i made sense
<script>
$(document).ready(function () {
$('.manuf').change(function () {
$.ajax({
type: "POST",
url: "ajax.aspx/GetModel",
data: '{' +
'ManufID:"' + $('.manuf').val() + '"' +
'}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
var data = json_parse(msg.d);
if (data.error) {
alert("Error!");
return;
}
alert(data.model);
},
error: function(msg) {
alert('Get Details Failure: ' + msg);
}
});
});
});
</script>
My bad - you can write your ajax call like this -
$.ajax({ url :"/website/myurl", type:"POST", contentType:"application/json;", dataType:"json", data : "{ 'id' : '" + $("select[id*=selCurrentManuf]").val() + "' } ",
success : function (return_data) {
var data = $.parseJSON(return_data);
// code to add the contents of data to other list
$("select[id*=selCurrentModel]").empty().append($("<option>").attr("value","0").text("Choose..."));
// for the dropdown list clear all options and add a 'choose...' as the first option
$.each(data, function (i, d) { $("<option>").attr("value", d.k).text(d.v).appendTo($("select[id*=selCurrentModel]")); });
}, error:function () {
// handle error
}
});
I assume that you know how to fetch data from the backend via ajax. Something like this -
$.ajax({ url :"/website/myurl", type:"POST", dataType:"application/json"; data:"json",
success : function (return_data) {
var data = $.parseJSON(return_data);
// code to add the contents of data to other list
}, error:function () {
// handle error
}
});
Lets say you are getting it in a variable data which is an array.
You may try something like this -
$("select[id*=selCurrentModel]").empty().append($("<option>").attr("value", "0").text("Choose..."));
// for the dropdown list clear all options and add a 'choose...' as the first option
$.each(data, function (i, d) { $("<option>").attr("value", d.k).text(d.v).appendTo($("#ddlExperience")); });
// user $.each to iterate the data object which
You may try things on these lines.... Hope this helps.