I am using a JS method to assign the names of computer languages to data attribute of div
e.g
<div id="Languages" data-Languages=''></div>
and js code
var langs='["Perl", "PHP", "Python", "Ruby", "Scala", "C#"]';
$('#Languages').data('Languages', langs);
but when i type text in the textbox it gives me an error
Object Expected
i am using this line for autocomplete
$(function () {
$("#tags").autocomplete({ source: $('#Languages').data('Languages') });
});
it works totally fine when i make another variable and pass it as a source as implemented in jquery website
i want to handle it with div's data attribute because in future i want to use JSON that fetches autocomplete data on page load and assign it to div data attribute.
sorry if that question sounds stupid, its my 2nd day with jquery and all that stuff.
Not sure if this is your problem exactly but you have single quotes around your array, making it a string.
it should be:
var langs = ["Perl", "PHP", "Python", "Ruby", "Scala", "C#"];
your langs is like '' which makes it a string. you need an array which behaves like a source for autocomplete. Also there is a mismatch in id and key of data you are trying. try this
var langs = ["Perl", "PHP", "Python", "Ruby", "Scala", "C#"];
$('#locations').data('languages', langs);
$(function () { $("#tags").autocomplete({
source: $('#locations').data('languages') });
});
problem is you are assigning data to div outside page ready function, when div is not actually been loaded on page. try below mentions code, it works fine for me.
$(function () {
var langs = ["Perl", "PHP", "Python", "Ruby", "Scala", "C#"];
$('#locations').data('languages', langs);
$("#tags").autocomplete({
source: $('#locations').data('languages') });
});
This is not much different from #Rahul solution.
but maybe you want to read directly from the data attribute:
var langs = ["Perl", "PHP", "Python", "Ruby", "Scala", "C#"];
$('#locations').attr('data-Languages', langs);
$(function () { $("#tags").autocomplete({
source: $('#locations').data('languages').split(',')});
});
working example: http://jsbin.com/oyusub/4/
Related
I am using following code and it always picks up hard coded data defined in availableTags. If I dynamically load data from C# WebApi, it still picks up old data i.e. ActionScript and AppleScript.
As you can see I am printing Before and After values and they both are working correctly i.e. as I can see it assigns new data to availableTags but autocomplete still works on old data. Is there a limit on how many items can I define in availableTags? Because dynamically it is getting 504 items from my code so may be this is the issue?
What am I doing wrong?
<input id="tags">
<script>
var availableTags =
[
"ActionScript",
"AppleScript"
];
$("#tags").autocomplete
({
source: availableTags
});
$.getJSON("MyController/GetAllTags")
.done(function (data)
{
alert("Before="+ availableTags);
availableTags = data;
alert("After="+ availableTags);
});
</script>
Try this
<input id="tags">
<script>
var availableTags =
[
"ActionScript",
"AppleScript"
];
$("#tags").autocomplete
({
source: availableTags
});
$.getJSON("MyController/GetAllTags")
.done(function (data)
{
$("#tag").autocomplete('option', 'source', data)
});
</script>
Edit 1: Updating Code
I am implementing a simple JQuery autocomplete with few entries so I don't need to use a web method. The code is like this:
$( function() {
var availableTags = [
"ActionScript",
"AppleScript"
];
$( "#tags" ).autocomplete({
source: availableTags
});
} );
The entries availableTags are unique to the user so they need to come from the server. How should I get the entries from the server side to the JavaScript in ASP.NET Core?
This assumes you have some service IUserTagService like this, registered through dependency injection:
public interface IUserTagService
{
IList<string> GetUserTags();
}
Since you don’t want (or need) an AJAX call here to load the tags after the page has been rendered, we’re just going to render the tags directly into the output. For that, we basically convert the returned list from the GetUserTags method into JSON and put this into a script tag. So the end result will look mostly like your static example.
So in the .cshtml view, we first inject our service. We can use the #inject directive at the beginning of the file for this:
#inject IUserTagService userTagService;
Then, we simply open a script tag and write the output into a variable:
<script>
$(function() {
var availableTags = #Json.Serialize(userTagService.GetUserTags());
$("#tags").autocomplete({
source: availableTags
});
});
</script>
This uses the Json.Serialize which is a utility function that is available in views to serialize the list into JSON.
You can make an ajax call to your server action method which returns the list as JSON array.
$(function () {
$.getJSON("#Url.Action("GetItems")", function (availableTags) {
$( "#tags" ).autocomplete({
source: availableTags
});
});
})
Assuming your GetItems action method returns the list of items as json array
public JsonResult GetItems()
{
var list = new List<string>() {"ActionScript","AppleScript"};
return new JsonResult(list);
}
Another option is to load the data (list of strings to your main views GET action method and in the razor view, convert that to a JS Array
So in your GET action,
var list = new List<string>() {"ActionScript","AppleScript"};
ViewBag.Items = list;
return View();
and in the razor view,
#section Scripts
{
<script>
$(function() {
var availableTags = #Html.Raw(Newtonsoft.Json.JsonConvert
.SerializeObject(ViewBag.Items));
$( "#tags" ).autocomplete({
source: availableTags
});
});
</script>
}
Dependency injection is possible in asp.net core views now. poke's answer above uses that. You may consider doing that instead of the ViewBag solution above.
When I change my dropdown list, I want change a label (lblCustomer).
I don't know how to get value from resource file.Any ideas!?
.text('"<%$ Resources:lblCustomer%>"'); this not work. 10x
$(function () {
$('#<%= ddlCustomer.ClientID %>').change(function ()
{
$('#<%= lblCustomer.ClientID %>').text('"<%$ Resources:lblCustomer%>"');
})
}
);
I had similar problem to this. What I end up doing is registering a startup script that reads the values from the .resx file into a variable in javascript. Then I just reference the javascript variables as I need to.
C# Code:
StringBuilder colModel = new StringBuilder();
colModel.AppendFormat("var uiStrings = {{ captureStart: \"{7}\", captureOK: \"{0}\", captureRegister: \"{1}\", captureBad: \"{2}\", captureRegisterBad: \"{8}\", gridTitle: \"{3}\", gridIsCap: \"{4}\", gridNoCap: \"{5}\", gridDelete: \"{6}\", captureDiffUser: \"{9}\" }};",
this.GetLocalResourceObject("capOK").ToString(), this.GetLocalResourceObject("capRegisterOK").ToString(), this.GetLocalResourceObject("capBad").ToString(),
this.GetLocalResourceObject("gvCaption").ToString(), this.GetLocalResourceObject("gvIsCaptured").ToString(), this.GetLocalResourceObject("gvIsNotCaptured").ToString(),
this.GetLocalResourceObject("gvDelete").ToString(), this.GetLocalResourceObject("capStart").ToString(), this.GetLocalResourceObject("capRegisterBad").ToString(),
this.GetLocalResourceObject("capDiffUser").ToString());
ClientScript.RegisterStartupScript(this.GetType(), "initData", colModel.ToString(), true);
JavaScript:
$("#status").html(uiStrings.captureDiffUser);
Hope this helps!
You can use the GetGolabalRessourceObject Function.
$(function () {
$('#<%= ddlCustomer.ClientID %>').change(function ()
{
$('#<%=lblCustomer.ClientID%>').text('<%=GetGlobalResourceObject("lblCustomer")%>');
})
}
);
I am trying to access the script variable pic and assign it to another variable in C#, say hidden field hdn. The script below is also placed on the same code behind page for some reason. I can directly access the hidden field here. But how do I assign it value from the script variable?
<script type=\"text/javascript\">
$(document).ready(function() {
$.get('<%=completeURL%>',
function(d) {
$(d).find('entry').each(function(){
var $entry = $(this);
var pic = $entry.find('content').attr('src');
alert(pic);
});
});
});
</script>
There is no way to assign a C# variable by javascript.
You have to send that value from the client (where you JavaScript is running) to the Server, and assign it.
This is so called ajax request, just google it and you'll find millions of good examples of how to achieve that.
create a hidden filed and then set the value from javascript
<asp:hiddenfield id="hf_MyValue"
value="whatever"
runat="server"/>
How To Set value in javascript
//get value from hidden filed
var test= document.getElementById('<%= hf_MyValue.ClientID %>');
//set value in hidden filed
document.getElementById('<%= hfBrand.ClientID %>').value = "True";
Create a hidden variable like this,
<input type="hidden" id="hdnVariable" runat="server" />
Now try this code
<script type=\"text/javascript\">
$(document).ready(function() {
$.get('<%=completeURL%>',
function(d) {
$(d).find('entry').each(function(){
var $entry = $(this);
var pic = $entry.find('content').attr('src');
//assign value to server side hidden variable
$("#<%=hdnVariable.ClientID%>").val(pic);
});
});
});
</script>
Now you can access this hidden field from C# code like this
string pic=hdnVariable.Value;
Basically, I have a dynamically created list and I have no idea in advance how many items there will be.
I need each one to launch a slightly different Ajax function on clicking.
I am currently using JQM for the modal boxes (happy to switch if someone knows something better).
The following code works fine for making all .ajaxpopup items launch the same page :
$().ready(function () {
$('#dialog').jqm({ ajax: "/QuestionManager/AjaxPopup/1", trigger: ".ajaxpopup" });
$(".ajaxpopup").click(function (e) {
e.preventDefault();
});
However, I need each item to launch a different page (1/2... I don't know the ID in advance).
I really like Adam's answer about adding a data-itemid tag to the element, but, I just can't seem to actually make this work.
I do not know if this is a JQM limitation or due to the way it is initiated.
The closest I have come is:
$(document).on("click", "a", function () {
var itemId = $(this).data("itemid");
$('#dialog').jqm({ ajax: "/QuestionManager/AjaxPopup/"+itemId, trigger: ".ajaxpopup" });
});
I have also replaced the dialog line with alert(itemId), which is giving the correct result, so, I know I am along the right path - I just can't seem to get this done!
Can anyone help?
You can wire dyanmically added content to respond to events via jQuery's live and on functions.
So if I'm understanding your particular case, you want those text nodes, when clicked, to launch a jqm modal? And you want your model's itemId to be a part of it?
First, add the itemId to your text via a data attribute:
#foreach (var item in Model.Routines)
{
<text data-itemid='#item.itemId'></text>
} //(sorry if the razor syntax is off a bit - that's not my expertise
And then:
$(document).on("click", "text", function() {
var itemId = $(this).data("itemid");
var textnodeText = $(this).text();
$('#dialog').jqm({ ajax: "/QuestionManager/_AjaxCreateQuestionInitial/" + textnodeText,
trigger: itemId });
});
EDIT
Based on your comment, if you have this html:
Add Data
You can handle the click event like this:
$(document).on("click", "a", function() {
var itemId = $(this).data("itemid");
//now run your ajax call
});
Why not create an JsonResult providing Action on your Contoller, that would provide list of items you need? Once that is in place I would iterate over the JSON array and prodce the boxes.
assuming your data would be (an example - this needs to be produced by your controller)
var data = [
{"Id": 1, "Name": "A"},
{"Id": 2, "Name": "B"},
{"Id": 3, "Name": "C"}
];
Your javascript (jquery) loop to handle your boxes would be
$.each(data, function(i, item) {
//replace with your dialog code
alert(data[i].Id+" "+data[i].Name);
});