Search Results

Search found 23820 results on 953 pages for 'jquery ui autocomplete'.

Page 1/953 | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • jQuery autocomplete disabled makes autocomplete partially transparent, not disabled

    - by Ryan Giglio
    I'm using the jQuery UI's "autocomplete" function on a search on my site. When you change a radio button from 'area search" to "name search" I want it to disable the autocomplete, and re-enable it when you switch back. However, when you disable the autocomplete it doesn't hide the dropdown, it just dims it to 20% opacity or so. Here's my javascript: var allFields = new Array(<?php echo $allFields ?>); $(document).ready(function() { if ($("input[name='searchType']:checked").val() == 'areaCode') { $("#siteSearch").autocomplete({ source: allFields, minLength: 2 }); } $("input[name='searchType']").change(function(){ if ($("input[name='searchType']:checked").val() == 'areaCode') { $( "#siteSearch" ).autocomplete( "option", "disabled", false ); alert("enabled"); } else { $( "#siteSearch" ).autocomplete( "option", "disabled", true ); alert("disabled"); } }); }); You can see it happening at http://crewinyourcode.com First you have to chose an area code to search, and then you can see the issue.

    Read the article

  • jQuery Autocomplete plug-in search configuration

    - by dev.e.loper
    I'm looking into using jQuery autocomplete plug-in to implement user lookup by first or last name. It looks like by default autocomplete looks up words by character sequence no matter its occurrence in a word. So if you have data such as: javascript, asp, haskell and you type in 'as' you will get all three. I would like it to at least match beginning of the word. So in above example you get only 'asp'. Is there a way to configure jQuery Autocomplete plug-in to do this? Ultimately it would be even better to match by beginning of first or last name like it is in Gmail.

    Read the article

  • jquery ui autocomplete problem

    - by Roger
    Hi, i've got a select box containing countries, and when one is selected, i want my autocomplete data for the city field to load via ajax. here's my code: // Sets up the autocompleter depending on the currently // selected country $(document).ready(function() { var cache = getCities(); $('#registration_city_id').autocomplete( { source: cache } ); cache = getCities(); // update the cache array when a different country is selected $("#registration_country_id").change(function() { cache = getCities(); }); }); /** * Gets the cities associated with the currently selected country */ function getCities() { var cityId = $("#registration_country_id :selected").attr('value'); return $.getJSON("/ajax/cities/" + cityId + ".html"); } This returns the following json: ["Aberdare","Aberdeen","Aberystwyth","Abingdon","Accrington","Airdrie","Aldershot","Alfreton","Alloa","Altrincham","Amersham","Andover","Antrim","Arbroath","Ardrossan","Arnold","Ashford","Ashington","Ashton-under-Lyne","Atherton","Aylesbury","Ayr",... ] But, it doesn't work. When i start typing in the city box, the style changes so the autocompleter is doing something, but it won't display this data. If i hard-code the above it works. Can anyone see what's wrong? Thanks

    Read the article

  • jquery ui autocomplete not working in ie8 (until page refresh)

    - by Andy Simpson
    Hello all, I am using jquery ui autocomplete it is working absolutely fine in all browsers except ie8. I have been doing some testing and there seems to be a strange bug. When I click on a link leading to the relevant page there is the following error generated by ie8 when I start typing in the autocomplete box: 'object doesn't support this property or method' this error points to my development jquery(1.4.2) file at line 4955, char 5 which is the following line: return new window.XMLHttpRequest(); However, if I simply reload the page the autocomplete works. I have added a random bit of data to be called with the autocomplete as I read that ie8 caches it ajax get requests but this does not seem to have solved the problem. Could there be a problem with the timing of the loading of all the relevant files including jquery? If so, how would I fix this? Any other clever ideas?! Andy

    Read the article

  • jquery autocomplete filtering

    - by eidylon
    Hello all, I have a page, which uses jQuery Autocomplete on the second two textboxes (investigator and institution). It is getting the data fine, and displaying it, but for some reason it is not filtering the list of data as i continue to type. Anyone know why? Is there something i need to do to turn this on? According to the jQuery site, the only options to the autocomplete initializer are delay, minLength and source. Thanks in advance! I'm using jQ v1.4.1 and jQui v.1.8rc1. Below is the code which I am calling on $(document).ready(). function hookUpAutoCompletes() { $('table#params input[name=sinvestigator]').autocomplete({ source: "json-investigators.asp", minLength: 2 }) $('table#params input[name=sinstitution]').autocomplete({ source: "json-institutions.asp", minLength: 2 }) }

    Read the article

  • jQuery UI Tabs Plugin Broke

    - by Warren J Thompson
    We are using the jquery ui tabs arrow plugin from this fiddle: http://jsfiddle.net/dECtZ/282/, but like many plugins, it breaks with the latest version of jQuery. We were able to get the csscur to work, but still get the following error in the jquery core (line 353): Uncaught TypeError: Cannot assign to read only property 'length' of function (e,t){if(!this._createWidget)return new o(e,t);arguments.length&&this._createWidget(e,t)} Code is as follows: (function($, undefined) { if (!$.xui) { $.xui = {}; } var tabs = $.extend({}, $.ui.tabs.prototype), _super = { _create: tabs._create, _destroy: tabs._destroy, _update: tabs._update }; $.xui.tabs = $.extend(tabs, { options: $.extend({}, tabs.options, { scrollable: false, changeOnScroll: false, closable: false, resizable: false, resizeHandles: "e,s,se" }), _create: function() { var self = this, o = self.options; _super._create.apply(self); if (o.scrollable) { self.element.addClass("ui-tabs-scrollable"); var scrollContainer = $('<div class="ui-tabs-scroll-container"></div>').prependTo(this.element); self.header = $('<div class="ui-tabs-nav-scrollable ui-widget-header ui-corner-all"></div>').prependTo(scrollContainer); var nav = self.element.find(".ui-tabs-nav:first").removeClass("ui-widget-header ui-corner-all").appendTo(this.header); var arrowsNav = $('<ol class="ui-helper-reset ui-helper-clearfix ui-tabs-nav-arrows"></ol>').prependTo(self.element); var navPrev = $('<li class="ui-tabs-arrow-previous ui-state-default ui-corner-bl ui-corner-tl" title="Previous"><a href="#"><span class="ui-icon ui-icon-carat-1-w">Previous tab</span></a></li>').prependTo(arrowsNav).hide(), navNext = $('<li class="ui-tabs-arrow-next ui-state-default ui-corner-tr ui-corner-br" title="Next"><a href="#"><span class="ui-icon ui-icon-carat-1-e">Next tab</span></a></li>').appendTo(arrowsNav).hide(); var scrollTo = function(to, delay) { var navWidth = 0, arrowWidth = navPrev.outerWidth(), marginLeft = -(parseInt(nav.css("marginLeft"), 10)), hwidth = self.header.width(), newMargin = 0; nav.find("li").each(function() { navWidth += $(this).outerWidth(true); }); if (to instanceof $.Event) { } else { newMargin = marginLeft+to; if (newMargin > (navWidth-hwidth)) { newMargin = (navWidth-hwidth); } else if (newMargin < 0) { newMargin = 0; } nav.stop(true).animate({ marginLeft: -(newMargin) }, delay, function(){ $(window).trigger("resize.tabs"); }); } } var holdTimer = false; navPrev.add(navNext).bind({ "click": function(e) { var isNext = this === navNext[0]; e.preventDefault(); if (o.changeOnScroll) { self.select(self.options.selected + (isNext ? 1 : -1)); } else { if (!holdTimer) scrollTo(isNext ? 150 : -150, 250); } }, "mousedown": function(e){ if (!o.changeOnScroll) { var isNext = this === navNext[0], duration = 10, pos = 15, timer; if (holdTimer) clearTimeout(holdTimer); holdTimer = setTimeout(timer = function(){ scrollTo(isNext ? pos : -(pos), duration); holdTimer = setTimeout(arguments.callee, duration); }, 150); } }, "mouseup mouseout": function(e){ if (!o.changeOnScroll) { clearTimeout(holdTimer); holdTimer = false; nav.stop(); } } }); self.header.bind('mousewheel', function(e, d, dX, dY) { e.preventDefault(); if (d === -1) { navNext.click(); } else if (d === 1) { navPrev.click(); } }); $(window).bind("resize.tabs", function(e) { var navWidth = 0; var arrowWidth = navPrev.outerWidth(); nav.find("li").each(function() { navWidth += $(this).outerWidth(true); }); var marginLeft = -(parseInt(nav.css("marginLeft"), 10)), hwidth = self.header.width(); if (navWidth > (hwidth+marginLeft)) { self.header.addClass("ui-tabs-arrow-r"); navNext.show("fade"); if (marginLeft > 0) { self.header.addClass("ui-tabs-arrow-l"); navPrev.show("fade"); } else { self.header.removeClass("ui-tabs-arrow-l"); navPrev.hide("fade"); } } else { self.header.removeClass("ui-tabs-arrows ui-tabs-arrow-l"); navNext.hide("fade"); if (marginLeft > 0) { self.header.addClass("ui-tabs-arrow-l"); navPrev.show("fade"); } else { self.header.removeClass("ui-tabs-arrow-l"); navPrev.hide("fade"); } } }).trigger("resize.tabs"); arrowsNav.find("li").bind({ "mouseenter focus": function(e) { $(this).addClass("ui-state-hover"); }, "mouseleave blur": function(e) { $(this).removeClass("ui-state-hover"); } }); this.anchors.bind("click.tabs", function(){ var li = $(this).parent(), arrowWidth = navPrev.outerWidth(), width = li.outerWidth(true), hwidth = self.header.width(), pos = li.position().left, marginLeft = -(parseInt(nav.stop(true,true).css("marginLeft"),10)), newMargin = -1; if (li.index() === 0) { newMargin = 0; } else if ((pos+width) >= (hwidth+marginLeft)) { newMargin = pos-hwidth+width; if ((li.index()+1) < nav.find("li").length) { newMargin += arrowWidth; } } else if (pos < marginLeft) { newMargin = pos-arrowWidth; } if (newMargin > -1) { nav.animate({ marginLeft: -(newMargin) }, 250, function(){ $(window).trigger("resize.tabs"); }); } }); } return self; }, _update: function(){ console.log(arguments); _super._update.apply(this); } }); $.widget("xui.tabs", $.xui.tabs); })(jQuery); $(function() { $("#tabs").tabs({ scrollable: true, changeOnScroll: false, closable: true }); $("#switcher").themeswitcher(); });

    Read the article

  • jQuery AutoComplete Plugin not working for JSON Response (sValue.substring is not a function)

    - by Sunday Ironfoot
    I'm trying to use the autocomplete plugin for jQuery (this one http://docs.jquery.com/Plugins/Autocomplete). My server is returning JSON string, which I'm trying to process on the client via AutoComplete plugin's 'parse' and 'formatItem' parameters, like so: $(document).ready(function() { $('.searchBox input.textbox').autocomplete('/DoSearch.aspx', { mustMatch: false, autoFill: true, minChars: 1, dataType: 'json', parse: function(data) { var array = new Array(); for (var i = 0; i < data.length; i++) { array[array.length] = { data: data[i], value: data[i].ID, result: data[i].ID }; } return array; }, formatItem: function(row, i, n) { return row.ID + ': ' + row.Title; } }); }); When I run this I get a 'sValue.substring is not a function' error thrown in Firebug. However, if I stick breakpoints on formatItem and parse function, they are hit as expected and contain valid data it seems. Here is an exact copy 'n' paste of the JSON text that gets returned from the server: [{"ID":140177,"Title":"Food Handling","Code":"J01.576.423.200"},{"ID":140178,"Title":"Food Handling","Code":"J01.576.423.200"},{"ID":140179,"Title":"Brain Infarction","Code":"C10.228.140.300.301.200"},{"ID":140180,"Title":"Cerebral Hemorrhage","Code":"C10.228.140.300.535.200"},{"ID":140182,"Title":"Insulin","Code":"D06.472.610.575"},{"ID":140183,"Title":"Insulin","Code":"D06.472.610.575"},{"ID":140184,"Title":"Insulin","Code":"D06.472.610.575"},{"ID":140186,"Title":"Insulin","Code":"D06.472.610.575"},{"ID":140188,"Title":"Insulin","Code":"D06.472.610.575"},{"ID":140189,"Title":"Sulfonylurea Compounds","Code":"D02.886.590.795"}] Please help, I've already searched Google and StackOverflow for help, but can't find anyone having else this error, cheers!

    Read the article

  • jQuery UI AutoComplete remote json response question

    - by Greg-J
    I was using geonames.org to autocomplete city and state but found it to be far too slow to be reliable. My code is as follows, and does work (wait about 10 seconds to see the autocomplete results) Old (working) code here: http://jsbin.com/umewo3/2/edit Now I am using YQL as they provide a much quicker response. The issue is that I don't seem to understand how to properly map the response. You can see I am sending a well formed request, and getting the response back - but I am somehow not dealing with the response properly. New (broken) code here: http://jsbin.com/aqoke3/2/edit Any and all help appreciated.

    Read the article

  • Microsoft and jQuery

    - by Rick Strahl
    The jQuery JavaScript library has been steadily getting more popular and with recent developments from Microsoft, jQuery is also getting ever more exposure on the ASP.NET platform including now directly from Microsoft. jQuery is a light weight, open source DOM manipulation library for JavaScript that has changed how many developers think about JavaScript. You can download it and find more information on jQuery on www.jquery.com. For me jQuery has had a huge impact on how I develop Web applications and was probably the main reason I went from dreading to do JavaScript development to actually looking forward to implementing client side JavaScript functionality. It has also had a profound impact on my JavaScript skill level for me by seeing how the library accomplishes things (and often reviewing the terse but excellent source code). jQuery made an uncomfortable development platform (JavaScript + DOM) a joy to work on. Although jQuery is by no means the only JavaScript library out there, its ease of use, small size, huge community of plug-ins and pure usefulness has made it easily the most popular JavaScript library available today. As a long time jQuery user, I’ve been excited to see the developments from Microsoft that are bringing jQuery to more ASP.NET developers and providing more integration with jQuery for ASP.NET’s core features rather than relying on the ASP.NET AJAX library. Microsoft and jQuery – making Friends jQuery is an open source project but in the last couple of years Microsoft has really thrown its weight behind supporting this open source library as a supported component on the Microsoft platform. When I say supported I literally mean supported: Microsoft now offers actual tech support for jQuery as part of their Product Support Services (PSS) as jQuery integration has become part of several of the ASP.NET toolkits and ships in several of the default Web project templates in Visual Studio 2010. The ASP.NET MVC 3 framework (still in Beta) also uses jQuery for a variety of client side support features including client side validation and we can look forward toward more integration of client side functionality via jQuery in both MVC and WebForms in the future. In other words jQuery is becoming an optional but included component of the ASP.NET platform. PSS support means that support staff will answer jQuery related support questions as part of any support incidents related to ASP.NET which provides some piece of mind to some corporate development shops that require end to end support from Microsoft. In addition to including jQuery and supporting it, Microsoft has also been getting involved in providing development resources for extending jQuery’s functionality via plug-ins. Microsoft’s last version of the Microsoft Ajax Library – which is the successor to the native ASP.NET AJAX Library – included some really cool functionality for client templates, databinding and localization. As it turns out Microsoft has rebuilt most of that functionality using jQuery as the base API and provided jQuery plug-ins of these components. Very recently these three plug-ins were submitted and have been approved for inclusion in the official jQuery plug-in repository and been taken over by the jQuery team for further improvements and maintenance. Even more surprising: The jQuery-templates component has actually been approved for inclusion in the next major update of the jQuery core in jQuery V1.5, which means it will become a native feature that doesn’t require additional script files to be loaded. Imagine this – an open source contribution from Microsoft that has been accepted into a major open source project for a core feature improvement. Microsoft has come a long way indeed! What the Microsoft Involvement with jQuery means to you For Microsoft jQuery support is a strategic decision that affects their direction in client side development, but nothing stopped you from using jQuery in your applications prior to Microsoft’s official backing and in fact a large chunk of developers did so readily prior to Microsoft’s announcement. Official support from Microsoft brings a few benefits to developers however. jQuery support in Visual Studio 2010 means built-in support for jQuery IntelliSense, automatically added jQuery scripts in many projects types and a common base for client side functionality that actually uses what most developers are already using. If you have already been using jQuery and were worried about straying from the Microsoft line and their internal Microsoft Ajax Library – worry no more. With official support and the change in direction towards jQuery Microsoft is now following along what most in the ASP.NET community had already been doing by using jQuery, which is likely the reason for Microsoft’s shift in direction in the first place. ASP.NET AJAX and the Microsoft AJAX Library weren’t bad technology – there was tons of useful functionality buried in these libraries. However, these libraries never got off the ground, mainly because early incarnations were squarely aimed at control/component developers rather than application developers. For all the functionality that these controls provided for control developers they lacked in useful and easily usable application developer functionality that was easily accessible in day to day client side development. The result was that even though Microsoft shipped support for these tools in the box (in .NET 3.5 and 4.0), other than for the internal support in ASP.NET for things like the UpdatePanel and the ASP.NET AJAX Control Toolkit as well as some third party vendors, the Microsoft client libraries were largely ignored by the developer community opening the door for other client side solutions. Microsoft seems to be acknowledging developer choice in this case: Many more developers were going down the jQuery path rather than using the Microsoft built libraries and there seems to be little sense in continuing development of a technology that largely goes unused by the majority of developers. Kudos for Microsoft for recognizing this and gracefully changing directions. Note that even though there will be no further development in the Microsoft client libraries they will continue to be supported so if you’re using them in your applications there’s no reason to start running for the exit in a panic and start re-writing everything with jQuery. Although that might be a reasonable choice in some cases, jQuery and the Microsoft libraries work well side by side so that you can leave existing solutions untouched even as you enhance them with jQuery. The Microsoft jQuery Plug-ins – Solid Core Features One of the most interesting developments in Microsoft’s embracing of jQuery is that Microsoft has started contributing to jQuery via standard mechanism set for jQuery developers: By submitting plug-ins. Microsoft took some of the nicest new features of the unpublished Microsoft Ajax Client Library and re-wrote these components for jQuery and then submitted them as plug-ins to the jQuery plug-in repository. Accepted plug-ins get taken over by the jQuery team and that’s exactly what happened with the three plug-ins submitted by Microsoft with the templating plug-in even getting slated to be published as part of the jQuery core in the next major release (1.5). The following plug-ins are provided by Microsoft: jQuery Templates – a client side template rendering engine jQuery Data Link – a client side databinder that can synchronize changes without code jQuery Globalization – provides formatting and conversion features for dates and numbers The first two are ports of functionality that was slated for the Microsoft Ajax Library while functionality for the globalization library provides functionality that was already found in the original ASP.NET AJAX library. To me all three plug-ins address a pressing need in client side applications and provide functionality I’ve previously used in other incarnations, but with more complete implementations. Let’s take a close look at these plug-ins. jQuery Templates http://api.jquery.com/category/plugins/templates/ Client side templating is a key component for building rich JavaScript applications in the browser. Templating on the client lets you avoid from manually creating markup by creating DOM nodes and injecting them individually into the document via code. Rather you can create markup templates – similar to the way you create classic ASP server markup – and merge data into these templates to render HTML which you can then inject into the document or replace existing content with. Output from templates are rendered as a jQuery matched set and can then be easily inserted into the document as needed. Templating is key to minimize client side code and reduce repeated code for rendering logic. Instead a single template can be used in many places for updating and adding content to existing pages. Further if you build pure AJAX interfaces that rely entirely on client rendering of the initial page content, templates allow you to a use a single markup template to handle all rendering of each specific HTML section/element. I’ve used a number of different client rendering template engines with jQuery in the past including jTemplates (a PHP style templating engine) and a modified version of John Resig’s MicroTemplating engine which I built into my own set of libraries because it’s such a commonly used feature in my client side applications. jQuery templates adds a much richer templating model that allows for sub-templates and access to the data items. Like John Resig’s original Micro Template engine, the core basics of the templating engine create JavaScript code which means that templates can include JavaScript code. To give you a basic idea of how templates work imagine I have an application that downloads a set of stock quotes based on a symbol list then displays them in the document. To do this you can create an ‘item’ template that describes how each of the quotes is renderd as a template inside of the document: <script id="stockTemplate" type="text/x-jquery-tmpl"> <div id="divStockQuote" class="errordisplay" style="width: 500px;"> <div class="label">Company:</div><div><b>${Company}(${Symbol})</b></div> <div class="label">Last Price:</div><div>${LastPrice}</div> <div class="label">Net Change:</div><div> {{if NetChange > 0}} <b style="color:green" >${NetChange}</b> {{else}} <b style="color:red" >${NetChange}</b> {{/if}} </div> <div class="label">Last Update:</div><div>${LastQuoteTimeString}</div> </div> </script> The ‘template’ is little more than HTML with some markup expressions inside of it that define the template language. Notice the embedded ${} expressions which reference data from the quote objects returned from an AJAX call on the server. You can embed any JavaScript or value expression in these template expressions. There are also a number of structural commands like {{if}} and {{each}} that provide for rudimentary logic inside of your templates as well as commands ({{tmpl}} and {{wrap}}) for nesting templates. You can find more about the full set of markup expressions available in the documentation. To load up this data you can use code like the following: <script type="text/javascript"> //var Proxy = new ServiceProxy("../PageMethods/PageMethodsService.asmx/"); $(document).ready(function () { $("#btnGetQuotes").click(GetQuotes); }); function GetQuotes() { var symbols = $("#txtSymbols").val().split(","); $.ajax({ url: "../PageMethods/PageMethodsService.asmx/GetStockQuotes", data: JSON.stringify({ symbols: symbols }), // parameter map type: "POST", // data has to be POSTed contentType: "application/json", timeout: 10000, dataType: "json", success: function (result) { var quotes = result.d; var jEl = $("#stockTemplate").tmpl(quotes); $("#quoteDisplay").empty().append(jEl); }, error: function (xhr, status) { alert(status + "\r\n" + xhr.responseText); } }); }; </script> In this case an ASMX AJAX service is called to retrieve the stock quotes. The service returns an array of quote objects. The result is returned as an object with the .d property (in Microsoft service style) that returns the actual array of quotes. The template is applied with: var jEl = $("#stockTemplate").tmpl(quotes); which selects the template script tag and uses the .tmpl() function to apply the data to it. The result is a jQuery matched set of elements that can then be appended to the quote display element in the page. The template is merged against an array in this example. When the result is an array the template is automatically applied to each each array item. If you pass a single data item – like say a stock quote – the template works exactly the same way but is applied only once. Templates also have access to a $data item which provides the current data item and information about the tempalte that is currently executing. This makes it possible to keep context within the context of the template itself and also to pass context from a parent template to a child template which is very powerful. Templates can be evaluated by using the template selector and calling the .tmpl() function on the jQuery matched set as shown above or you can use the static $.tmpl() function to provide a template as a string. This allows you to dynamically create templates in code or – more likely – to load templates from the server via AJAX calls. In short there are options The above shows off some of the basics, but there’s much for functionality available in the template engine. Check the documentation link for more information and links to additional examples. The plug-in download also comes with a number of examples that demonstrate functionality. jQuery templates will become a native component in jQuery Core 1.5, so it’s definitely worthwhile checking out the engine today and get familiar with this interface. As much as I’m stoked about templating becoming part of the jQuery core because it’s such an integral part of many applications, there are also a couple shortcomings in the current incarnation: Lack of Error Handling Currently if you embed an expression that is invalid it’s simply not rendered. There’s no error rendered into the template nor do the various  template functions throw errors which leaves finding of bugs as a runtime exercise. I would like some mechanism – optional if possible – to be able to get error info of what is failing in a template when it’s rendered. No String Output Templates are always rendered into a jQuery matched set and there’s no way that I can see to directly render to a string. String output can be useful for debugging as well as opening up templating for creating non-HTML string output. Limited JavaScript Access Unlike John Resig’s original MicroTemplating Engine which was entirely based on JavaScript code generation these templates are limited to a few structured commands that can ‘execute’. There’s no code execution inside of script code which means you’re limited to calling expressions available in global objects or the data item passed in. This may or may not be a big deal depending on the complexity of your template logic. Error handling has been discussed quite a bit and it’s likely there will be some solution to that particualar issue by the time jQuery templates ship. The others are relatively minor issues but something to think about anyway. jQuery Data Link http://api.jquery.com/category/plugins/data-link/ jQuery Data Link provides the ability to do two-way data binding between input controls and an underlying object’s properties. The typical scenario is linking a textbox to a property of an object and have the object updated when the text in the textbox is changed and have the textbox change when the value in the object or the entire object changes. The plug-in also supports converter functions that can be applied to provide the conversion logic from string to some other value typically necessary for mapping things like textbox string input to say a number property and potentially applying additional formatting and calculations. In theory this sounds great, however in reality this plug-in has some serious usability issues. Using the plug-in you can do things like the following to bind data: person = { firstName: "rick", lastName: "strahl"}; $(document).ready( function() { // provide for two-way linking of inputs $("form").link(person); // bind to non-input elements explicitly $("#objFirst").link(person, { firstName: { name: "objFirst", convertBack: function (value, source, target) { $(target).text(value); } } }); $("#objLast").link(person, { lastName: { name: "objLast", convertBack: function (value, source, target) { $(target).text(value); } } }); }); This code hooks up two-way linking between a couple of textboxes on the page and the person object. The first line in the .ready() handler provides mapping of object to form field with the same field names as properties on the object. Note that .link() does NOT bind items into the textboxes when you call .link() – changes are mapped only when values change and you move out of the field. Strike one. The two following commands allow manual binding of values to specific DOM elements which is effectively a one-way bind. You specify the object and a then an explicit mapping where name is an ID in the document. The converter is required to explicitly assign the value to the element. Strike two. You can also detect changes to the underlying object and cause updates to the input elements bound. Unfortunately the syntax to do this is not very natural as you have to rely on the jQuery data object. To update an object’s properties and get change notification looks like this: function updateFirstName() { $(person).data("firstName", person.firstName + " (code updated)"); } This works fine in causing any linked fields to be updated. In the bindings above both the firstName input field and objFirst DOM element gets updated. But the syntax requires you to use a jQuery .data() call for each property change to ensure that the changes are tracked properly. Really? Sure you’re binding through multiple layers of abstraction now but how is that better than just manually assigning values? The code savings (if any) are going to be minimal. As much as I would like to have a WPF/Silverlight/Observable-like binding mechanism in client script, this plug-in doesn’t help much towards that goal in its current incarnation. While you can bind values, the ‘binder’ is too limited to be really useful. If initial values can’t be assigned from the mappings you’re going to end up duplicating work loading the data using some other mechanism. There’s no easy way to re-bind data with a different object altogether since updates trigger only through the .data members. Finally, any non-input elements have to be bound via code that’s fairly verbose and frankly may be more voluminous than what you might write by hand for manual binding and unbinding. Two way binding can be very useful but it has to be easy and most importantly natural. If it’s more work to hook up a binding than writing a couple of lines to do binding/unbinding this sort of thing helps very little in most scenarios. In talking to some of the developers the feature set for Data Link is not complete and they are still soliciting input for features and functionality. If you have ideas on how you want this feature to be more useful get involved and post your recommendations. As it stands, it looks to me like this component needs a lot of love to become useful. For this component to really provide value, bindings need to be able to be refreshed easily and work at the object level, not just the property level. It seems to me we would be much better served by a model binder object that can perform these binding/unbinding tasks in bulk rather than a tool where each link has to be mapped first. I also find the choice of creating a jQuery plug-in questionable – it seems a standalone object – albeit one that relies on the jQuery library – would provide a more intuitive interface than the current forcing of options onto a plug-in style interface. Out of the three Microsoft created components this is by far the least useful and least polished implementation at this point. jQuery Globalization http://github.com/jquery/jquery-global Globalization in JavaScript applications often gets short shrift and part of the reason for this is that natively in JavaScript there’s little support for formatting and parsing of numbers and dates. There are a number of JavaScript libraries out there that provide some support for globalization, but most are limited to a particular portion of globalization. As .NET developers we’re fairly spoiled by the richness of APIs provided in the framework and when dealing with client development one really notices the lack of these features. While you may not necessarily need to localize your application the globalization plug-in also helps with some basic tasks for non-localized applications: Dealing with formatting and parsing of dates and time values. Dates in particular are problematic in JavaScript as there are no formatters whatsoever except the .toString() method which outputs a verbose and next to useless long string. With the globalization plug-in you get a good chunk of the formatting and parsing functionality that the .NET framework provides on the server. You can write code like the following for example to format numbers and dates: var date = new Date(); var output = $.format(date, "MMM. dd, yy") + "\r\n" + $.format(date, "d") + "\r\n" + // 10/25/2010 $.format(1222.32213, "N2") + "\r\n" + $.format(1222.33, "c") + "\r\n"; alert(output); This becomes even more useful if you combine it with templates which can also include any JavaScript expressions. Assuming the globalization plug-in is loaded you can create template expressions that use the $.format function. Here’s the template I used earlier for the stock quote again with a couple of formats applied: <script id="stockTemplate" type="text/x-jquery-tmpl"> <div id="divStockQuote" class="errordisplay" style="width: 500px;"> <div class="label">Company:</div><div><b>${Company}(${Symbol})</b></div> <div class="label">Last Price:</div> <div>${$.format(LastPrice,"N2")}</div> <div class="label">Net Change:</div><div> {{if NetChange > 0}} <b style="color:green" >${NetChange}</b> {{else}} <b style="color:red" >${NetChange}</b> {{/if}} </div> <div class="label">Last Update:</div> <div>${$.format(LastQuoteTime,"MMM dd, yyyy")}</div> </div> </script> There are also parsing methods that can parse dates and numbers from strings into numbers easily: alert($.parseDate("25.10.2010")); alert($.parseInt("12.222")); // de-DE uses . for thousands separators As you can see culture specific options are taken into account when parsing. The globalization plugin provides rich support for a variety of locales: Get a list of all available cultures Query cultures for culture items (like currency symbol, separators etc.) Localized string names for all calendar related items (days of week, months) Generated off of .NET’s supported locales In short you get much of the same functionality that you already might be using in .NET on the server side. The plugin includes a huge number of locales and an Globalization.all.min.js file that contains the text defaults for each of these locales as well as small locale specific script files that define each of the locale specific settings. It’s highly recommended that you NOT use the huge globalization file that includes all locales, but rather add script references to only those languages you explicitly care about. Overall this plug-in is a welcome helper. Even if you use it with a single locale (like en-US) and do no other localization, you’ll gain solid support for number and date formatting which is a vital feature of many applications. Changes for Microsoft It’s good to see Microsoft coming out of its shell and away from the ‘not-built-here’ mentality that has been so pervasive in the past. It’s especially good to see it applied to jQuery – a technology that has stood in drastic contrast to Microsoft’s own internal efforts in terms of design, usage model and… popularity. It’s great to see that Microsoft is paying attention to what customers prefer to use and supporting the customer sentiment – even if it meant drastically changing course of policy and moving into a more open and sharing environment in the process. The additional jQuery support that has been introduced in the last two years certainly has made lives easier for many developers on the ASP.NET platform. It’s also nice to see Microsoft submitting proposals through the standard jQuery process of plug-ins and getting accepted for various very useful projects. Certainly the jQuery Templates plug-in is going to be very useful to many especially since it will be baked into the jQuery core in jQuery 1.5. I hope we see more of this type of involvement from Microsoft in the future. Kudos!© Rick Strahl, West Wind Technologies, 2005-2010Posted in jQuery  ASP.NET  

    Read the article

  • Is there more than one jQuery Autocomplete widget?

    - by Cheeso
    I thought there was only one - included in jQuery UI and documented here. I know there are third-party autocomplete widgets that plug-in to jQuery, like the one from devbridge. But I would describe that as an autocomplete widget for jQuery, rather than the jQuery autocomplete widget. But on Stackoverflow, I see questions asking about an autocomplete widget that does not use the syntax described in the jQuery UI documentation. For example: jquery.autocomplete.js - how does autocomplete work? Jquery AutoComplete Plugin calling Help with jquery autocomplete and json response The jQuery UI syntax looks like this: $("#input1").autocomplete({ source: function(req, responseFn) { ... }, select: function(value, data){ ... } }); Whereas some of those other questions hae a syntax like this: $("#city").autocomplete("CUList.asmx/GetCUList", { dataType: 'jsonp', parse: function(data) { var rows = new Array(); for(var i=0; i<data.length; i++){ rows[i] = { data:data[i], value:data[i].CUName, result:data[i].CUName }; } return rows; }, formatItem: function(row, i, n) { return row.CUName + ', ' + row.CUCity; }, max: 50 }); What's the explanation for the discrepancy? People ask about "jquery autocomplete" without specifying which one. With no direction, shouldn't I assume THE jquery UI autocomplete?

    Read the article

  • Add a link to a JQueryUI autocomplete item

    - by Tordek
    When a user starts typing on the searchbox, the suggestion page returns the latest item from all collections matching that nama, plus other data. I'd like to show that item (along its image), and a link to "see all items from this collection". I can do (most of) that with the following code: $('#search').autocomplete({ source: function (request, response) { $.ajax({ url: suggesturl, dataType: 'json', data: request, success: function (data) { response(data.map(function (value) { return { 'label': '<img src="' + value.thumbsmall + '" />' + value.name + '<a href="/">More items from this collection...</a>', 'value': value.fullname }; })); } }); }, minLength: 3 }) The problem is that, although the link appears in the box, when it's clicked it gets ignored, and the default select action is executed (the item's value is put into the textbox).

    Read the article

  • An Introduction to jQuery Templates

    - by Stephen Walther
    The goal of this blog entry is to provide you with enough information to start working with jQuery Templates. jQuery Templates enable you to display and manipulate data in the browser. For example, you can use jQuery Templates to format and display a set of database records that you have retrieved with an Ajax call. jQuery Templates supports a number of powerful features such as template tags, template composition, and wrapped templates. I’ll concentrate on the features that I think that you will find most useful. In order to focus on the jQuery Templates feature itself, this blog entry is server technology agnostic. All the samples use HTML pages instead of ASP.NET pages. In a future blog entry, I’ll focus on using jQuery Templates with ASP.NET Web Forms and ASP.NET MVC (You can do some pretty powerful things when jQuery Templates are used on the client and ASP.NET is used on the server). Introduction to jQuery Templates The jQuery Templates plugin was developed by the Microsoft ASP.NET team in collaboration with the open-source jQuery team. While working at Microsoft, I wrote the original proposal for jQuery Templates, Dave Reed wrote the original code, and Boris Moore wrote the final code. The jQuery team – especially John Resig – was very involved in each step of the process. Both the jQuery community and ASP.NET communities were very active in providing feedback. jQuery Templates will be included in the jQuery core library (the jQuery.js library) when jQuery 1.5 is released. Until jQuery 1.5 is released, you can download the jQuery Templates plugin from the jQuery Source Code Repository or you can use jQuery Templates directly from the ASP.NET CDN. The documentation for jQuery Templates is already included with the official jQuery documentation at http://api.jQuery.com. The main entry for jQuery templates is located under the topic plugins/templates. A Basic Sample of jQuery Templates Let’s start with a really simple sample of using jQuery Templates. We’ll use the plugin to display a list of books stored in a JavaScript array. Here’s the complete code: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html > <head> <title>Intro</title> <link href="0_Site.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="pageContent"> <h1>ASP.NET Bookstore</h1> <div id="bookContainer"></div> </div> <script id="bookTemplate" type="text/x-jQuery-tmpl"> <div> <img src="BookPictures/${picture}" alt="" /> <h2>${title}</h2> price: ${formatPrice(price)} </div> </script> <script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.4.4.js"></script> <script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.templates/beta1/jquery.tmpl.js"></script> <script type="text/javascript"> // Create an array of books var books = [ { title: "ASP.NET 4 Unleashed", price: 37.79, picture: "AspNet4Unleashed.jpg" }, { title: "ASP.NET MVC Unleashed", price: 44.99, picture: "AspNetMvcUnleashed.jpg" }, { title: "ASP.NET Kick Start", price: 4.00, picture: "AspNetKickStart.jpg" }, { title: "ASP.NET MVC Unleashed iPhone", price: 44.99, picture: "AspNetMvcUnleashedIPhone.jpg" }, ]; // Render the books using the template $("#bookTemplate").tmpl(books).appendTo("#bookContainer"); function formatPrice(price) { return "$" + price.toFixed(2); } </script> </body> </html> When you open this page in a browser, a list of books is displayed: There are several things going on in this page which require explanation. First, notice that the page uses both the jQuery 1.4.4 and jQuery Templates libraries. Both libraries are retrieved from the ASP.NET CDN: <script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.4.4.js"></script> <script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.templates/beta1/jquery.tmpl.js"></script> You can use the ASP.NET CDN for free (even for production websites). You can learn more about the files included on the ASP.NET CDN by visiting the ASP.NET CDN documentation page. Second, you should notice that the actual template is included in a script tag with a special MIME type: <script id="bookTemplate" type="text/x-jQuery-tmpl"> <div> <img src="BookPictures/${picture}" alt="" /> <h2>${title}</h2> price: ${formatPrice(price)} </div> </script> This template is displayed for each of the books rendered by the template. The template displays a book picture, title, and price. Notice that the SCRIPT tag which wraps the template has a MIME type of text/x-jQuery-tmpl. Why is the template wrapped in a SCRIPT tag and why the strange MIME type? When a browser encounters a SCRIPT tag with an unknown MIME type, it ignores the content of the tag. This is the behavior that you want with a template. You don’t want a browser to attempt to parse the contents of a template because this might cause side effects. For example, the template above includes an <img> tag with a src attribute that points at “BookPictures/${picture}”. You don’t want the browser to attempt to load an image at the URL “BookPictures/${picture}”. Instead, you want to prevent the browser from processing the IMG tag until the ${picture} expression is replaced by with the actual name of an image by the jQuery Templates plugin. If you are not worried about browser side-effects then you can wrap a template inside any HTML tag that you please. For example, the following DIV tag would also work with the jQuery Templates plugin: <div id="bookTemplate" style="display:none"> <div> <h2>${title}</h2> price: ${formatPrice(price)} </div> </div> Notice that the DIV tag includes a style=”display:none” attribute to prevent the template from being displayed until the template is parsed by the jQuery Templates plugin. Third, notice that the expression ${…} is used to display the value of a JavaScript expression within a template. For example, the expression ${title} is used to display the value of the book title property. You can use any JavaScript function that you please within the ${…} expression. For example, in the template above, the book price is formatted with the help of the custom JavaScript formatPrice() function which is defined lower in the page. Fourth, and finally, the template is rendered with the help of the tmpl() method. The following statement selects the bookTemplate and renders an array of books using the bookTemplate. The results are appended to a DIV element named bookContainer by using the standard jQuery appendTo() method. $("#bookTemplate").tmpl(books).appendTo("#bookContainer"); Using Template Tags Within a template, you can use any of the following template tags. {{tmpl}} – Used for template composition. See the section below. {{wrap}} – Used for wrapped templates. See the section below. {{each}} – Used to iterate through a collection. {{if}} – Used to conditionally display template content. {{else}} – Used with {{if}} to conditionally display template content. {{html}} – Used to display the value of an HTML expression without encoding the value. Using ${…} or {{= }} performs HTML encoding automatically. {{= }}-- Used in exactly the same way as ${…}. {{! }} – Used for displaying comments. The contents of a {{!...}} tag are ignored. For example, imagine that you want to display a list of blog entries. Each blog entry could, possibly, have an associated list of categories. The following page illustrates how you can use the { if}} and {{each}} template tags to conditionally display categories for each blog entry:   <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>each</title> <link href="1_Site.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="blogPostContainer"></div> <script id="blogPostTemplate" type="text/x-jQuery-tmpl"> <h1>${postTitle}</h1> <p> ${postEntry} </p> {{if categories}} Categories: {{each categories}} <i>${$value}</i> {{/each}} {{else}} Uncategorized {{/if}} </script> <script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.4.4.js"></script> <script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.templates/beta1/jquery.tmpl.js"></script> <script type="text/javascript"> var blogPosts = [ { postTitle: "How to fix a sink plunger in 5 minutes", postEntry: "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Maecenas porttitor congue massa. Fusce posuere, magna sed pulvinar ultricies, purus lectus malesuada libero, sit amet commodo magna eros quis urna.", categories: ["HowTo", "Sinks", "Plumbing"] }, { postTitle: "How to remove a broken lightbulb", postEntry: "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Maecenas porttitor congue massa. Fusce posuere, magna sed pulvinar ultricies, purus lectus malesuada libero, sit amet commodo magna eros quis urna.", categories: ["HowTo", "Lightbulbs", "Electricity"] }, { postTitle: "New associate website", postEntry: "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Maecenas porttitor congue massa. Fusce posuere, magna sed pulvinar ultricies, purus lectus malesuada libero, sit amet commodo magna eros quis urna." } ]; // Render the blog posts $("#blogPostTemplate").tmpl(blogPosts).appendTo("#blogPostContainer"); </script> </body> </html> When this page is opened in a web browser, the following list of blog posts and categories is displayed: Notice that the first and second blog entries have associated categories but the third blog entry does not. The third blog entry is “Uncategorized”. The template used to render the blog entries and categories looks like this: <script id="blogPostTemplate" type="text/x-jQuery-tmpl"> <h1>${postTitle}</h1> <p> ${postEntry} </p> {{if categories}} Categories: {{each categories}} <i>${$value}</i> {{/each}} {{else}} Uncategorized {{/if}} </script> Notice the special expression $value used within the {{each}} template tag. You can use $value to display the value of the current template item. In this case, $value is used to display the value of each category in the collection of categories. Template Composition When building a fancy page, you might want to build a template out of multiple templates. In other words, you might want to take advantage of template composition. For example, imagine that you want to display a list of products. Some of the products are being sold at their normal price and some of the products are on sale. In that case, you might want to use two different templates for displaying a product: a productTemplate and a productOnSaleTemplate. The following page illustrates how you can use the {{tmpl}} tag to build a template from multiple templates:   <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Composition</title> <link href="2_Site.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="pageContainer"> <h1>Products</h1> <div id="productListContainer"></div> <!-- Show list of products using composition --> <script id="productListTemplate" type="text/x-jQuery-tmpl"> <div> {{if onSale}} {{tmpl "#productOnSaleTemplate"}} {{else}} {{tmpl "#productTemplate"}} {{/if}} </div> </script> <!-- Show product --> <script id="productTemplate" type="text/x-jQuery-tmpl"> ${name} </script> <!-- Show product on sale --> <script id="productOnSaleTemplate" type="text/x-jQuery-tmpl"> <b>${name}</b> <img src="images/on_sale.png" alt="On Sale" /> </script> <script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.4.4.js"></script> <script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.templates/beta1/jquery.tmpl.js"></script> <script type="text/javascript"> var products = [ { name: "Laptop", onSale: false }, { name: "Apples", onSale: true }, { name: "Comb", onSale: false } ]; $("#productListTemplate").tmpl(products).appendTo("#productListContainer"); </script> </div> </body> </html>   In the page above, the main template used to display the list of products looks like this: <script id="productListTemplate" type="text/x-jQuery-tmpl"> <div> {{if onSale}} {{tmpl "#productOnSaleTemplate"}} {{else}} {{tmpl "#productTemplate"}} {{/if}} </div> </script>   If a product is on sale then the product is displayed with the productOnSaleTemplate (which includes an on sale image): <script id="productOnSaleTemplate" type="text/x-jQuery-tmpl"> <b>${name}</b> <img src="images/on_sale.png" alt="On Sale" /> </script>   Otherwise, the product is displayed with the normal productTemplate (which does not include the on sale image): <script id="productTemplate" type="text/x-jQuery-tmpl"> ${name} </script>   You can pass a parameter to the {{tmpl}} tag. The parameter becomes the data passed to the template rendered by the {{tmpl}} tag. For example, in the previous section, we used the {{each}} template tag to display a list of categories for each blog entry like this: <script id="blogPostTemplate" type="text/x-jQuery-tmpl"> <h1>${postTitle}</h1> <p> ${postEntry} </p> {{if categories}} Categories: {{each categories}} <i>${$value}</i> {{/each}} {{else}} Uncategorized {{/if}} </script>   Another way to create this template is to use template composition like this: <script id="blogPostTemplate" type="text/x-jQuery-tmpl"> <h1>${postTitle}</h1> <p> ${postEntry} </p> {{if categories}} Categories: {{tmpl(categories) "#categoryTemplate"}} {{else}} Uncategorized {{/if}} </script> <script id="categoryTemplate" type="text/x-jQuery-tmpl"> <i>${$data}</i> &nbsp; </script>   Using the {{each}} tag or {{tmpl}} tag is largely a matter of personal preference. Wrapped Templates The {{wrap}} template tag enables you to take a chunk of HTML and transform the HTML into another chunk of HTML (think easy XSLT). When you use the {{wrap}} tag, you work with two templates. The first template contains the HTML being transformed and the second template includes the filter expressions for transforming the HTML. For example, you can use the {{wrap}} template tag to transform a chunk of HTML into an interactive tab strip: When you click any of the tabs, you see the corresponding content. This tab strip was created with the following page: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Wrapped Templates</title> <style type="text/css"> body { font-family: Arial; background-color:black; } .tabs div { display:inline-block; border-bottom: 1px solid black; padding:4px; background-color:gray; cursor:pointer; } .tabs div.tabState_true { background-color:white; border-bottom:1px solid white; } .tabBody { border-top:1px solid white; padding:10px; background-color:white; min-height:400px; width:400px; } </style> </head> <body> <div id="tabsView"></div> <script id="tabsContent" type="text/x-jquery-tmpl"> {{wrap "#tabsWrap"}} <h3>Tab 1</h3> <div> Content of tab 1. Lorem ipsum dolor <b>sit</b> amet, consectetuer adipiscing elit. Maecenas porttitor congue massa. Fusce posuere, magna sed pulvinar ultricies, purus lectus malesuada libero, sit amet commodo magna eros quis urna. </div> <h3>Tab 2</h3> <div> Content of tab 2. Lorem ipsum dolor <b>sit</b> amet, consectetuer adipiscing elit. Maecenas porttitor congue massa. Fusce posuere, magna sed pulvinar ultricies, purus lectus malesuada libero, sit amet commodo magna eros quis urna. </div> <h3>Tab 3</h3> <div> Content of tab 3. Lorem ipsum dolor <b>sit</b> amet, consectetuer adipiscing elit. Maecenas porttitor congue massa. Fusce posuere, magna sed pulvinar ultricies, purus lectus malesuada libero, sit amet commodo magna eros quis urna. </div> {{/wrap}} </script> <script id="tabsWrap" type="text/x-jquery-tmpl"> <div class="tabs"> {{each $item.html("h3", true)}} <div class="tabState_${$index === selectedTabIndex}"> ${$value} </div> {{/each}} </div> <div class="tabBody"> {{html $item.html("div")[selectedTabIndex]}} </div> </script> <script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.4.4.js"></script> <script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.templates/beta1/jquery.tmpl.js"></script> <script type="text/javascript"> // Global for tracking selected tab var selectedTabIndex = 0; // Render the tab strip $("#tabsContent").tmpl().appendTo("#tabsView"); // When a tab is clicked, update the tab strip $("#tabsView") .delegate(".tabState_false", "click", function () { var templateItem = $.tmplItem(this); selectedTabIndex = $(this).index(); templateItem.update(); }); </script> </body> </html>   The “source” for the tab strip is contained in the following template: <script id="tabsContent" type="text/x-jquery-tmpl"> {{wrap "#tabsWrap"}} <h3>Tab 1</h3> <div> Content of tab 1. Lorem ipsum dolor <b>sit</b> amet, consectetuer adipiscing elit. Maecenas porttitor congue massa. Fusce posuere, magna sed pulvinar ultricies, purus lectus malesuada libero, sit amet commodo magna eros quis urna. </div> <h3>Tab 2</h3> <div> Content of tab 2. Lorem ipsum dolor <b>sit</b> amet, consectetuer adipiscing elit. Maecenas porttitor congue massa. Fusce posuere, magna sed pulvinar ultricies, purus lectus malesuada libero, sit amet commodo magna eros quis urna. </div> <h3>Tab 3</h3> <div> Content of tab 3. Lorem ipsum dolor <b>sit</b> amet, consectetuer adipiscing elit. Maecenas porttitor congue massa. Fusce posuere, magna sed pulvinar ultricies, purus lectus malesuada libero, sit amet commodo magna eros quis urna. </div> {{/wrap}} </script>   The tab strip is created with a list of H3 elements (which represent each tab) and DIV elements (which represent the body of each tab). Notice that the HTML content is wrapped in the {{wrap}} template tag. This template tag points at the following tabsWrap template: <script id="tabsWrap" type="text/x-jquery-tmpl"> <div class="tabs"> {{each $item.html("h3", true)}} <div class="tabState_${$index === selectedTabIndex}"> ${$value} </div> {{/each}} </div> <div class="tabBody"> {{html $item.html("div")[selectedTabIndex]}} </div> </script> The tabs DIV contains all of the tabs. The {{each}} template tag is used to loop through each of the H3 elements from the source template and render a DIV tag that represents a particular tab. The template item html() method is used to filter content from the “source” HTML template. The html() method accepts a jQuery selector for its first parameter. The tabs are retrieved from the source template by using an h3 filter. The second parameter passed to the html() method – the textOnly parameter -- causes the filter to return the inner text of each h3 element. You can learn more about the html() method at the jQuery website (see the section on $item.html()). The tabBody DIV renders the body of the selected tab. Notice that the {{html}} template tag is used to display the tab body so that HTML content in the body won’t be HTML encoded. The html() method is used, once again, to grab all of the DIV elements from the source HTML template. The selectedTabIndex global variable is used to display the contents of the selected tab. Remote Templates A common feature request for jQuery templates is support for remote templates. Developers want to be able to separate templates into different files. Adding support for remote templates requires only a few lines of extra code (Dave Ward has a nice blog entry on this). For example, the following page uses a remote template from a file named BookTemplate.htm: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Remote Templates</title> <link href="0_Site.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="pageContent"> <h1>ASP.NET Bookstore</h1> <div id="bookContainer"></div> </div> <script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.4.4.js"></script> <script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.templates/beta1/jquery.tmpl.js"></script> <script type="text/javascript"> // Create an array of books var books = [ { title: "ASP.NET 4 Unleashed", price: 37.79, picture: "AspNet4Unleashed.jpg" }, { title: "ASP.NET MVC Unleashed", price: 44.99, picture: "AspNetMvcUnleashed.jpg" }, { title: "ASP.NET Kick Start", price: 4.00, picture: "AspNetKickStart.jpg" }, { title: "ASP.NET MVC Unleashed iPhone", price: 44.99, picture: "AspNetMvcUnleashedIPhone.jpg" }, ]; // Get the remote template $.get("BookTemplate.htm", null, function (bookTemplate) { // Render the books using the remote template $.tmpl(bookTemplate, books).appendTo("#bookContainer"); }); function formatPrice(price) { return "$" + price.toFixed(2); } </script> </body> </html>   The remote template is retrieved (and rendered) with the following code: // Get the remote template $.get("BookTemplate.htm", null, function (bookTemplate) { // Render the books using the remote template $.tmpl(bookTemplate, books).appendTo("#bookContainer"); });   This code uses the standard jQuery $.get() method to get the BookTemplate.htm file from the server with an Ajax request. After the BookTemplate.htm file is successfully retrieved, the $.tmpl() method is used to render an array of books with the template. Here’s what the BookTemplate.htm file looks like: <div> <img src="BookPictures/${picture}" alt="" /> <h2>${title}</h2> price: ${formatPrice(price)} </div> Notice that the template in the BooksTemplate.htm file is not wrapped by a SCRIPT element. There is no need to wrap the template in this case because there is no possibility that the template will get interpreted before you want it to be interpreted. If you plan to use the bookTemplate multiple times – for example, you are paging or sorting the books -- then you should compile the template into a function and cache the compiled template function. For example, the following page can be used to page through a list of 100 products (using iPhone style More paging). <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Template Caching</title> <link href="6_Site.css" rel="stylesheet" type="text/css" /> </head> <body> <h1>Products</h1> <div id="productContainer"></div> <button id="more">More</button> <script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.4.4.js"></script> <script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.templates/beta1/jquery.tmpl.js"></script> <script type="text/javascript"> // Globals var pageIndex = 0; // Create an array of products var products = []; for (var i = 0; i < 100; i++) { products.push({ name: "Product " + (i + 1) }); } // Get the remote template $.get("ProductTemplate.htm", null, function (productTemplate) { // Compile and cache the template $.template("productTemplate", productTemplate); // Render the products renderProducts(0); }); $("#more").click(function () { pageIndex++; renderProducts(); }); function renderProducts() { // Get page of products var pageOfProducts = products.slice(pageIndex * 5, pageIndex * 5 + 5); // Used cached productTemplate to render products $.tmpl("productTemplate", pageOfProducts).appendTo("#productContainer"); } function formatPrice(price) { return "$" + price.toFixed(2); } </script> </body> </html>   The ProductTemplate is retrieved from an external file named ProductTemplate.htm. This template is retrieved only once. Furthermore, it is compiled and cached with the help of the $.template() method: // Get the remote template $.get("ProductTemplate.htm", null, function (productTemplate) { // Compile and cache the template $.template("productTemplate", productTemplate); // Render the products renderProducts(0); });   The $.template() method compiles the HTML representation of the template into a JavaScript function and caches the template function with the name productTemplate. The cached template can be used by calling the $.tmp() method. The productTemplate is used in the renderProducts() method: function renderProducts() { // Get page of products var pageOfProducts = products.slice(pageIndex * 5, pageIndex * 5 + 5); // Used cached productTemplate to render products $.tmpl("productTemplate", pageOfProducts).appendTo("#productContainer"); } In the code above, the first parameter passed to the $.tmpl() method is the name of a cached template. Working with Template Items In this final section, I want to devote some space to discussing Template Items. A new Template Item is created for each rendered instance of a template. For example, if you are displaying a list of 100 products with a template, then 100 Template Items are created. A Template Item has the following properties and methods: data – The data associated with the Template Instance. For example, a product. tmpl – The template associated with the Template Instance. parent – The parent template item if the template is nested. nodes – The HTML content of the template. calls – Used by {{wrap}} template tag. nest – Used by {{tmpl}} template tag. wrap – Used to imperatively enable wrapped templates. html – Used to filter content from a wrapped template. See the above section on wrapped templates. update – Used to re-render a template item. The last method – the update() method -- is especially interesting because it enables you to re-render a template item with new data or even a new template. For example, the following page displays a list of books. When you hover your mouse over any of the books, additional book details are displayed. In the following screenshot, details for ASP.NET Kick Start are displayed. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Template Item</title> <link href="0_Site.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="pageContent"> <h1>ASP.NET Bookstore</h1> <div id="bookContainer"></div> </div> <script id="bookTemplate" type="text/x-jQuery-tmpl"> <div class="bookItem"> <img src="BookPictures/${picture}" alt="" /> <h2>${title}</h2> price: ${formatPrice(price)} </div> </script> <script id="bookDetailsTemplate" type="text/x-jQuery-tmpl"> <div class="bookItem"> <img src="BookPictures/${picture}" alt="" /> <h2>${title}</h2> price: ${formatPrice(price)} <p> ${description} </p> </div> </script> <script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.4.4.js"></script> <script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.templates/beta1/jquery.tmpl.js"></script> <script type="text/javascript"> // Create an array of books var books = [ { title: "ASP.NET 4 Unleashed", price: 37.79, picture: "AspNet4Unleashed.jpg", description: "The most comprehensive book on Microsoft’s new ASP.NET 4.. " }, { title: "ASP.NET MVC Unleashed", price: 44.99, picture: "AspNetMvcUnleashed.jpg", description: "Writing for professional programmers, Walther explains the crucial concepts that make the Model-View-Controller (MVC) development paradigm work…" }, { title: "ASP.NET Kick Start", price: 4.00, picture: "AspNetKickStart.jpg", description: "Visual Studio .NET is the premier development environment for creating .NET applications…." }, { title: "ASP.NET MVC Unleashed iPhone", price: 44.99, picture: "AspNetMvcUnleashedIPhone.jpg", description: "ASP.NET MVC Unleashed for the iPhone…" }, ]; // Render the books using the template $("#bookTemplate").tmpl(books).appendTo("#bookContainer"); // Get compiled details template var bookDetailsTemplate = $("#bookDetailsTemplate").template(); // Add hover handler $(".bookItem").mouseenter(function () { // Get template item associated with DIV var templateItem = $(this).tmplItem(); // Change template to compiled template templateItem.tmpl = bookDetailsTemplate; // Re-render template templateItem.update(); }); function formatPrice(price) { return "$" + price.toFixed(2); } </script> </body> </html>   There are two templates used to display a book: bookTemplate and bookDetailsTemplate. When you hover your mouse over a template item, the standard bookTemplate is swapped out for the bookDetailsTemplate. The bookDetailsTemplate displays a book description. The books are rendered with the bookTemplate with the following line of code: // Render the books using the template $("#bookTemplate").tmpl(books).appendTo("#bookContainer");   The following code is used to swap the bookTemplate and the bookDetailsTemplate to show details for a book: // Get compiled details template var bookDetailsTemplate = $("#bookDetailsTemplate").template(); // Add hover handler $(".bookItem").mouseenter(function () { // Get template item associated with DIV var templateItem = $(this).tmplItem(); // Change template to compiled template templateItem.tmpl = bookDetailsTemplate; // Re-render template templateItem.update(); });   When you hover your mouse over a DIV element rendered by the bookTemplate, the mouseenter handler executes. First, this handler retrieves the Template Item associated with the DIV element by calling the tmplItem() method. The tmplItem() method returns a Template Item. Next, a new template is assigned to the Template Item. Notice that a compiled version of the bookDetailsTemplate is assigned to the Template Item’s tmpl property. The template is compiled earlier in the code by calling the template() method. Finally, the Template Item update() method is called to re-render the Template Item with the bookDetailsTemplate instead of the original bookTemplate. Summary This is a long blog entry and I still have not managed to cover all of the features of jQuery Templates J However, I’ve tried to cover the most important features of jQuery Templates such as template composition, template wrapping, and template items. To learn more about jQuery Templates, I recommend that you look at the documentation for jQuery Templates at the official jQuery website. Another great way to learn more about jQuery Templates is to look at the (unminified) source code.

    Read the article

  • jQuery Templates and Data Linking (and Microsoft contributing to jQuery)

    - by ScottGu
    The jQuery library has a passionate community of developers, and it is now the most widely used JavaScript library on the web today. Two years ago I announced that Microsoft would begin offering product support for jQuery, and that we’d be including it in new versions of Visual Studio going forward. By default, when you create new ASP.NET Web Forms and ASP.NET MVC projects with VS 2010 you’ll find jQuery automatically added to your project. A few weeks ago during my second keynote at the MIX 2010 conference I announced that Microsoft would also begin contributing to the jQuery project.  During the talk, John Resig -- the creator of the jQuery library and leader of the jQuery developer team – talked a little about our participation and discussed an early prototype of a new client templating API for jQuery. In this blog post, I’m going to talk a little about how my team is starting to contribute to the jQuery project, and discuss some of the specific features that we are working on such as client-side templating and data linking (data-binding). Contributing to jQuery jQuery has a fantastic developer community, and a very open way to propose suggestions and make contributions.  Microsoft is following the same process to contribute to jQuery as any other member of the community. As an example, when working with the jQuery community to improve support for templating to jQuery my team followed the following steps: We created a proposal for templating and posted the proposal to the jQuery developer forum (http://forum.jquery.com/topic/jquery-templates-proposal and http://forum.jquery.com/topic/templating-syntax ). After receiving feedback on the forums, the jQuery team created a prototype for templating and posted the prototype at the Github code repository (http://github.com/jquery/jquery-tmpl ). We iterated on the prototype, creating a new fork on Github of the templating prototype, to suggest design improvements. Several other members of the community also provided design feedback by forking the templating code. There has been an amazing amount of participation by the jQuery community in response to the original templating proposal (over 100 posts in the jQuery forum), and the design of the templating proposal has evolved significantly based on community feedback. The jQuery team is the ultimate determiner on what happens with the templating proposal – they might include it in jQuery core, or make it an official plugin, or reject it entirely.  My team is excited to be able to participate in the open source process, and make suggestions and contributions the same way as any other member of the community. jQuery Template Support Client-side templates enable jQuery developers to easily generate and render HTML UI on the client.  Templates support a simple syntax that enables either developers or designers to declaratively specify the HTML they want to generate.  Developers can then programmatically invoke the templates on the client, and pass JavaScript objects to them to make the content rendered completely data driven.  These JavaScript objects can optionally be based on data retrieved from a server. Because the jQuery templating proposal is still evolving in response to community feedback, the final version might look very different than the version below. This blog post gives you a sense of how you can try out and use templating as it exists today (you can download the prototype by the jQuery core team at http://github.com/jquery/jquery-tmpl or the latest submission from my team at http://github.com/nje/jquery-tmpl).  jQuery Client Templates You create client-side jQuery templates by embedding content within a <script type="text/html"> tag.  For example, the HTML below contains a <div> template container, as well as a client-side jQuery “contactTemplate” template (within the <script type="text/html"> element) that can be used to dynamically display a list of contacts: The {{= name }} and {{= phone }} expressions are used within the contact template above to display the names and phone numbers of “contact” objects passed to the template. We can use the template to display either an array of JavaScript objects or a single object. The JavaScript code below demonstrates how you can render a JavaScript array of “contact” object using the above template. The render() method renders the data into a string and appends the string to the “contactContainer” DIV element: When the page is loaded, the list of contacts is rendered by the template.  All of this template rendering is happening on the client-side within the browser:   Templating Commands and Conditional Display Logic The current templating proposal supports a small set of template commands - including if, else, and each statements. The number of template commands was deliberately kept small to encourage people to place more complicated logic outside of their templates. Even this small set of template commands is very useful though. Imagine, for example, that each contact can have zero or more phone numbers. The contacts could be represented by the JavaScript array below: The template below demonstrates how you can use the if and each template commands to conditionally display and loop the phone numbers for each contact: If a contact has one or more phone numbers then each of the phone numbers is displayed by iterating through the phone numbers with the each template command: The jQuery team designed the template commands so that they are extensible. If you have a need for a new template command then you can easily add new template commands to the default set of commands. Support for Client Data-Linking The ASP.NET team recently submitted another proposal and prototype to the jQuery forums (http://forum.jquery.com/topic/proposal-for-adding-data-linking-to-jquery). This proposal describes a new feature named data linking. Data Linking enables you to link a property of one object to a property of another object - so that when one property changes the other property changes.  Data linking enables you to easily keep your UI and data objects synchronized within a page. If you are familiar with the concept of data-binding then you will be familiar with data linking (in the proposal, we call the feature data linking because jQuery already includes a bind() method that has nothing to do with data-binding). Imagine, for example, that you have a page with the following HTML <input> elements: The following JavaScript code links the two INPUT elements above to the properties of a JavaScript “contact” object that has a “name” and “phone” property: When you execute this code, the value of the first INPUT element (#name) is set to the value of the contact name property, and the value of the second INPUT element (#phone) is set to the value of the contact phone property. The properties of the contact object and the properties of the INPUT elements are also linked – so that changes to one are also reflected in the other. Because the contact object is linked to the INPUT element, when you request the page, the values of the contact properties are displayed: More interesting, the values of the linked INPUT elements will change automatically whenever you update the properties of the contact object they are linked to. For example, we could programmatically modify the properties of the “contact” object using the jQuery attr() method like below: Because our two INPUT elements are linked to the “contact” object, the INPUT element values will be updated automatically (without us having to write any code to modify the UI elements): Note that we updated the contact object above using the jQuery attr() method. In order for data linking to work, you must use jQuery methods to modify the property values. Two Way Linking The linkBoth() method enables two-way data linking. The contact object and INPUT elements are linked in both directions. When you modify the value of the INPUT element, the contact object is also updated automatically. For example, the following code adds a client-side JavaScript click handler to an HTML button element. When you click the button, the property values of the contact object are displayed using an alert() dialog: The following demonstrates what happens when you change the value of the Name INPUT element and click the Save button. Notice that the name property of the “contact” object that the INPUT element was linked to was updated automatically: The above example is obviously trivially simple.  Instead of displaying the new values of the contact object with a JavaScript alert, you can imagine instead calling a web-service to save the object to a database. The benefit of data linking is that it enables you to focus on your data and frees you from the mechanics of keeping your UI and data in sync. Converters The current data linking proposal also supports a feature called converters. A converter enables you to easily convert the value of a property during data linking. For example, imagine that you want to represent phone numbers in a standard way with the “contact” object phone property. In particular, you don’t want to include special characters such as ()- in the phone number - instead you only want digits and nothing else. In that case, you can wire-up a converter to convert the value of an INPUT element into this format using the code below: Notice above how a converter function is being passed to the linkFrom() method used to link the phone property of the “contact” object with the value of the phone INPUT element. This convertor function strips any non-numeric characters from the INPUT element before updating the phone property.  Now, if you enter the phone number (206) 555-9999 into the phone input field then the value 2065559999 is assigned to the phone property of the contact object: You can also use a converter in the opposite direction also. For example, you can apply a standard phone format string when displaying a phone number from a phone property. Combining Templating and Data Linking Our goal in submitting these two proposals for templating and data linking is to make it easier to work with data when building websites and applications with jQuery. Templating makes it easier to display a list of database records retrieved from a database through an Ajax call. Data linking makes it easier to keep the data and user interface in sync for update scenarios. Currently, we are working on an extension of the data linking proposal to support declarative data linking. We want to make it easy to take advantage of data linking when using a template to display data. For example, imagine that you are using the following template to display an array of product objects: Notice the {{link name}} and {{link price}} expressions. These expressions enable declarative data linking between the SPAN elements and properties of the product objects. The current jQuery templating prototype supports extending its syntax with custom template commands. In this case, we are extending the default templating syntax with a custom template command named “link”. The benefit of using data linking with the above template is that the SPAN elements will be automatically updated whenever the underlying “product” data is updated.  Declarative data linking also makes it easier to create edit and insert forms. For example, you could create a form for editing a product by using declarative data linking like this: Whenever you change the value of the INPUT elements in a template that uses declarative data linking, the underlying JavaScript data object is automatically updated. Instead of needing to write code to scrape the HTML form to get updated values, you can instead work with the underlying data directly – making your client-side code much cleaner and simpler. Downloading Working Code Examples of the Above Scenarios You can download this .zip file to get with working code examples of the above scenarios.  The .zip file includes 4 static HTML page: Listing1_Templating.htm – Illustrates basic templating. Listing2_TemplatingConditionals.htm – Illustrates templating with the use of the if and each template commands. Listing3_DataLinking.htm – Illustrates data linking. Listing4_Converters.htm – Illustrates using a converter with data linking. You can un-zip the file to the file-system and then run each page to see the concepts in action. Summary We are excited to be able to begin participating within the open-source jQuery project.  We’ve received lots of encouraging feedback in response to our first two proposals, and we will continue to actively contribute going forward.  These features will hopefully make it easier for all developers (including ASP.NET developers) to build great Ajax applications. Hope this helps, Scott P.S. [In addition to blogging, I am also now using Twitter for quick updates and to share links. Follow me at: twitter.com/scottgu]

    Read the article

  • jQuery UI Accordion CSS

    - by ScG
    I am planning to use the jQuery UI Accordion and also the default theme provided I see that the jQuery UI Accordion uses the following classes from this url link text <div class="ui-accordion ui-widget ui-helper-reset"> <h3 class="ui-accordion-header ui-helper-reset ui-state-active ui-corner-top"> <span class="ui-icon ui-icon-triangle-1-s"/> <a href="#">Section 1</a> </h3> <div class="ui-accordion-content ui-helper-reset ui-widget-content ui-corner-bottom ui-accordion-content-active"> Section 1 content </div> <h3 class="ui-accordion-header ui-helper-reset ui-state-default ui-corner-all"> <span class="ui-icon ui-icon-triangle-1-e"/> <a href="#">Section 2</a> </h3> <div class="ui-accordion-content ui-helper-reset ui-widget-content ui-corner-bottom"> Section 2 content </div> <h3 class="ui-accordion-header ui-helper-reset ui-state-default ui-corner-all"> <span class="ui-icon ui-icon-triangle-1-e"/> <a href="#">Section 3</a> </h3> <div class="ui-accordion-content ui-helper-reset ui-widget-content ui-corner-bottom"> Section 3 content </div> </div> I do not want to use the entire CSS from the theme file, just the ones required for the UI Accordion. However I am not able to create the same effect. Anyone can help?

    Read the article

  • jQuery autocomplete - update options on dynamically created elements

    - by Ian Robinson
    Background The user enters values into multiple inputs on the page. Think of entering a list of widgets for sale. The user would select the type of a widget from a drop down. Then enter the name of the Widget vendor, and then the actual name of the widget. These UI elements would all appear as one row. The user is able to click an "add another widget" link and a new row is created. The two input elements have autocomplete functionality attached to them using the DevBridge jQuery plugin. It suggests the name of the vendor and the name of the widget. I have recently wired up the logic to filter the name of the widget based on the name of the vendor you entered. This means setting the (custom) vendorName parameter when attaching the autocomplete plugin so it can be passed to the server side to retrieve the widget names for that vendor that match the name the user entered. To achieve this functionality I'm dynamically attaching the autocomplete functionality to the second element (the widget name text box) when it receives focus. Here is an example: $('.autocomplete-widget').live('focus', function () { $(this).autocomplete({ serviceUrl: '/something.ashx', params: { type: 'widget', vendorName: $(this).parent().prev().find('.autocomplete-vendor').val()} }); }); Problem At first glance, this looks to function quite well. However I started noticing some inconsistencies, and upon inspection, I found out that the call to the server is actually happening several times in some cases. Each time the widget name input element receives focus the autocomplete functionality is attached. And what I'm seeing is that the call to the server is made in proportion to how many times the input element has gained focus. I'd like to avoid making the call more than once, but retain the ability to attach (or update) the autocomplete functionality "on focus". I've tried to use the autocomplete 'setOptions' method but have only been able to get it to work with the static elements, not the dynamically created elements. Question Is there a way I can clear out the autocomplete functionality before I attach another one?

    Read the article

  • how to precompile a jquery ui autocomplete widget?

    - by Alex
    Hello, I have a jquery ui autocomplete widget in a form and I'd like to preselect its value from a database. My autocomplete works in the following way: the id is a number, tha label and the value are the same and are a concatenation of id + " - " + description. When a value from the autocomplete is selected, a hidden field's value is set to the value of id. Then, the hidden field value is saved to the db when the form is submitted. When the user comes back on the page for editing, I need to reload the value from the db: I set the idden field value again and then I would like to precompile the value of the autocomplete widget with the concatenation of id + " - " + description taken form the db. I think I should trigger the event of selecting a row in the autocomplete, but I don't know how to do. Do you have any ideas? Thank you Here is the code of the autocomplete: $('#codice_contratto').autocomplete({ source: 'do_contratto.php', select: function(event, ui) { $('#id_contratto').val(ui.item.id); } });

    Read the article

  • JQuery UI Autocomplete - disallow free text entry?

    - by JK
    Is it possible to disallow free text entry in the JQuery UI autocomplete widget? eg I only want the user to be allowed to select from the list of items that are presented in the autocomplete list, and dont want them to be able to write some random text. I didn't see anything in the demos/docs describing how to do this. http://jqueryui.com/demos/autocomplete/ I'm using autocomplete like this $('#selector').autocomplete({ source: url, minlength: 2, select: function (event, ui) { // etc }

    Read the article

  • Redirecting users on select from autocomplete?

    - by juno-2
    Hi, i'm trying to implement the jquery autocomplete plugin. I've got it up and running, but something is not working properly. Basically i have a autocomplete-list of employees. The list is generated from a table in a sql-database (employee_names and employee_ID), using a VB.NET handler (.ashx file). The data is formatted as: employee_name-employee_ID. So far so good and all employees are listed in autocomplete. The problem is that i don't know how to redirect a user to a certain page (for example employee_profile.aspx) when they've selected an employee from autocomplete. This is my redirect-code, but it ain't working like it should: $('#fname2').result(function(event, data, formatted) { location.href = "employee_profile.aspx?id=" + data }); For example; a user selects It will redirect a user to employee_profile.aspx?id=name of employee-id of employee (for example: employee_profile.aspx?id=John Doe-91210) instead of employee_profile.aspx?id=91210. I know i can strip the employee_ID with: formatResult: function(data, value) { return value.split("-")[1]; } }); But i do not know how to pass that employee_ID to the redirect-page.. Here my whole code: $().ready(function() { $("#fname2").autocomplete("AutocompleteData.ashx", { minChars: 3, selectFirst: false, formatItem: function(data, i, n, value) { return value.split("-")[0]; }, //Not used, just for splitting employee_ID //formatResult: function(data, value) { // return value.split("-")[1]; //} }); $('#fname2').result(function(event, data, formatted) { location.href = "employee_profile.aspx?id=" + data }); }); I know i'm very close and it should be something really simple, but can anyone help me out?

    Read the article

  • Ubuntu 12.04 + Eclipse 64 bits key binding error

    - by user110933
    The text is quite extense so, this is just a part of it: !SESSION 2012-11-23 10:15:52.442 ----------------------------------------------- eclipse.buildId=I20120608-1200 java.version=1.7.0_09 java.vendor=Oracle Corporation BootLoader constants: OS=linux, ARCH=x86_64, WS=gtk, NL=en_US Command-line arguments: -os linux -ws gtk -arch x86_64 !ENTRY org.eclipse.jface 2 0 2012-11-23 10:16:06.408 !MESSAGE Keybinding conflicts occurred. They may interfere with normal accelerator operation. !SUBENTRY 1 org.eclipse.jface 2 0 2012-11-23 10:16:06.408 !MESSAGE A conflict occurred for ALT+SHIFT+R: Binding(ALT+SHIFT+R, ParameterizedCommand(Command(oracle.eclipse.tools.common.services.ui.refactor.rename.command,Rename, Rename the selected text., Category(org.eclipse.jdt.ui.category.refactoring,Refactor - Java,Java Refactoring Actions,true), oracle.eclipse.tools.common.services.ui.refactor.internal.ArtifactRefactoringCommandHandler, ,,true),null), org.eclipse.ui.defaultAcceleratorConfiguration, org.eclipse.ui.contexts.window,,,system) Binding(ALT+SHIFT+R, ParameterizedCommand(Command(org.eclipse.jdt.ui.edit.text.java.rename.element,Rename - Refactoring , Rename the selected element, Category(org.eclipse.jdt.ui.category.refactoring,Refactor - Java,Java Refactoring Actions,true), , ,,true),null), org.eclipse.ui.defaultAcceleratorConfiguration, org.eclipse.ui.contexts.window,,,system) !ENTRY org.eclipse.ui.workbench 4 0 2012-11-23 10:16:10.409 !MESSAGE An unexpected exception was thrown. !STACK 0 java.lang.NullPointerException at org.eclipse.ui.internal.WorkbenchWindow.putToolbarLabel(WorkbenchWindow.java:1697) at org.eclipse.ui.internal.menus.MenuAdditionCacheEntry.createToolBarAdditionContribution(MenuAdditionCacheEntry.java:208) at org.eclipse.ui.internal.menus.MenuAdditionCacheEntry.createContributionItems(MenuAdditionCacheEntry.java:177) at org.eclipse.ui.internal.menus.TrimContributionManager.update(TrimContributionManager.java:224) at org.eclipse.ui.internal.WorkbenchWindow.updateLayoutDataForContents(WorkbenchWindow.java:3874) at org.eclipse.ui.internal.WorkbenchWindow.setCoolBarVisible(WorkbenchWindow.java:3675) at org.eclipse.ui.internal.ViewIntroAdapterPart.setBarVisibility(ViewIntroAdapterPart.java:203) at org.eclipse.ui.internal.ViewIntroAdapterPart.dispose(ViewIntroAdapterPart.java:106) at org.eclipse.ui.internal.WorkbenchPartReference.doDisposePart(WorkbenchPartReference.java:737) at org.eclipse.ui.internal.ViewReference.doDisposePart(ViewReference.java:107) at org.eclipse.ui.internal.WorkbenchPartReference.dispose(WorkbenchPartReference.java:684) at org.eclipse.ui.internal.WorkbenchPage.disposePart(WorkbenchPage.java:1801) at org.eclipse.ui.internal.WorkbenchPage.partRemoved(WorkbenchPage.java:1793) at org.eclipse.ui.internal.ViewFactory.releaseView(ViewFactory.java:257) at org.eclipse.ui.internal.Perspective.dispose(Perspective.java:292) at org.eclipse.ui.internal.WorkbenchPage.dispose(WorkbenchPage.java:1872) at org.eclipse.ui.internal.WorkbenchWindow.closeAllPages(WorkbenchWindow.java:894) at org.eclipse.ui.internal.WorkbenchWindow.hardClose(WorkbenchWindow.java:1729) at org.eclipse.ui.internal.WorkbenchWindow.busyClose(WorkbenchWindow.java:730) at org.eclipse.ui.internal.WorkbenchWindow.access$0(WorkbenchWindow.java:715) at org.eclipse.ui.internal.WorkbenchWindow$6.run(WorkbenchWindow.java:867) at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java:70) at org.eclipse.ui.internal.WorkbenchWindow.close(WorkbenchWindow.java:865) at org.eclipse.jface.window.WindowManager.close(WindowManager.java:109) at org.eclipse.ui.internal.Workbench$18.run(Workbench.java:1114) at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) at org.eclipse.ui.internal.Workbench.busyClose(Workbench.java:1111) at org.eclipse.ui.internal.Workbench.access$15(Workbench.java:1040) at org.eclipse.ui.internal.Workbench$25.run(Workbench.java:1284) at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java:70) at org.eclipse.ui.internal.Workbench.close(Workbench.java:1282) at org.eclipse.ui.internal.Workbench.close(Workbench.java:1254) at org.eclipse.ui.internal.WorkbenchWindow.busyClose(WorkbenchWindow.java:727) at org.eclipse.ui.internal.WorkbenchWindow.access$0(WorkbenchWindow.java:715) at org.eclipse.ui.internal.WorkbenchWindow$6.run(WorkbenchWindow.java:867) at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java:70) at org.eclipse.ui.internal.WorkbenchWindow.close(WorkbenchWindow.java:865) at org.eclipse.jface.window.Window.handleShellCloseEvent(Window.java:741) at org.eclipse.jface.window.Window$3.shellClosed(Window.java:687) at org.eclipse.swt.widgets.TypedListener.handleEvent(TypedListener.java:98) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:84) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1276) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1300) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1285) at org.eclipse.swt.widgets.Shell.closeWidget(Shell.java:617) at org.eclipse.swt.widgets.Shell.gtk_delete_event(Shell.java:1191) at org.eclipse.swt.widgets.Widget.windowProc(Widget.java:1750) at org.eclipse.swt.widgets.Control.windowProc(Control.java:5116) at org.eclipse.swt.widgets.Display.windowProc(Display.java:4369) at org.eclipse.swt.internal.gtk.OS._gtk_main_do_event(Native Method) at org.eclipse.swt.internal.gtk.OS.gtk_main_do_event(OS.java:8295) at org.eclipse.swt.widgets.Display.eventProc(Display.java:1192) at org.eclipse.swt.internal.gtk.OS._g_main_context_iteration(Native Method) at org.eclipse.swt.internal.gtk.OS.g_main_context_iteration(OS.java:2332) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3177) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:2701) at org.eclipse.ui.internal.Workbench.runUI(Workbench.java:2665) at org.eclipse.ui.internal.Workbench.access$4(Workbench.java:2499) at org.eclipse.ui.internal.Workbench$7.run(Workbench.java:679) at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:332) at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:668) at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:149) at org.eclipse.ui.internal.ide.application.IDEApplication.start(IDEApplication.java:124) at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:196) at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:110) at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:79) at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:353) at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:180) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:601) at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:629) at org.eclipse.equinox.launcher.Main.basicRun(Main.java:584) at org.eclipse.equinox.launcher.Main.run(Main.java:1438) at org.eclipse.equinox.launcher.Main.main(Main.java:1414) !SESSION 2012-11-23 10:36:07.863 ----------------------------------------------- eclipse.buildId=I20120608-1200 java.version=1.7.0_09 java.vendor=Oracle Corporation BootLoader constants: OS=linux, ARCH=x86_64, WS=gtk, NL=en_US Command-line arguments: -os linux -ws gtk -arch x86_64 !ENTRY org.eclipse.jface 2 0 2012-11-23 10:36:13.181 !MESSAGE Keybinding conflicts occurred. They may interfere with normal accelerator operation. !SUBENTRY 1 org.eclipse.jface 2 0 2012-11-23 10:36:13.181 !MESSAGE A conflict occurred for ALT+SHIFT+R: Binding(ALT+SHIFT+R, ParameterizedCommand(Command(oracle.eclipse.tools.common.services.ui.refactor.rename.command,Rename, Rename the selected text., Category(org.eclipse.jdt.ui.category.refactoring,Refactor - Java,Java Refactoring Actions,true), oracle.eclipse.tools.common.services.ui.refactor.internal.ArtifactRefactoringCommandHandler, ,,true),null), org.eclipse.ui.defaultAcceleratorConfiguration, org.eclipse.ui.contexts.window,,,system) Binding(ALT+SHIFT+R, ParameterizedCommand(Command(org.eclipse.jdt.ui.edit.text.java.rename.element,Rename - Refactoring , Rename the selected element, Category(org.eclipse.jdt.ui.category.refactoring,Refactor - Java,Java Refactoring Actions,true), , ,,true),null), org.eclipse.ui.defaultAcceleratorConfiguration, org.eclipse.ui.contexts.window,,,system) !ENTRY org.eclipse.osgi 2 1 2012-11-23 10:39:04.681 !MESSAGE NLS unused message: CacheManager_CannotLoadNonUrlLocation in: org.eclipse.equinox.internal.p2.repository.messages !SESSION 2012-11-23 15:14:12.933 ----------------------------------------------- eclipse.buildId=I20120608-1200 java.version=1.7.0_09 java.vendor=Oracle Corporation BootLoader constants: OS=linux, ARCH=x86_64, WS=gtk, NL=en_US Command-line arguments: -os linux -ws gtk -arch x86_64 !ENTRY org.eclipse.jface 2 0 2012-11-23 15:14:23.380 !MESSAGE Keybinding conflicts occurred. They may interfere with normal accelerator operation. !SUBENTRY 1 org.eclipse.jface 2 0 2012-11-23 15:14:23.380 !MESSAGE A conflict occurred for ALT+SHIFT+R: Binding(ALT+SHIFT+R, ParameterizedCommand(Command(oracle.eclipse.tools.common.services.ui.refactor.rename.command,Rename, Rename the selected text., Category(org.eclipse.jdt.ui.category.refactoring,Refactor - Java,Java Refactoring Actions,true), oracle.eclipse.tools.common.services.ui.refactor.internal.ArtifactRefactoringCommandHandler, ,,true),null), org.eclipse.ui.defaultAcceleratorConfiguration, org.eclipse.ui.contexts.window,,,system) Binding(ALT+SHIFT+R, ParameterizedCommand(Command(org.eclipse.jdt.ui.edit.text.java.rename.element,Rename - Refactoring , Rename the selected element, Category(org.eclipse.jdt.ui.category.refactoring,Refactor - Java,Java Refactoring Actions,true), , ,,true),null), org.eclipse.ui.defaultAcceleratorConfiguration, org.eclipse.ui.contexts.window,,,system) !ENTRY org.springframework.ide.eclipse.uaa 4 2 2012-11-23 15:14:32.800 !MESSAGE Problems occurred when invoking code from plug-in: "org.springframework.ide.eclipse.uaa". !STACK 0 java.lang.NullPointerException at org.springframework.ide.eclipse.internal.uaa.monitor.CommandUsageMonitor.startMonitoring(CommandUsageMonitor.java:61) at org.springframework.ide.eclipse.uaa.UaaPlugin$1$1.run(UaaPlugin.java:91) at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) at org.springframework.ide.eclipse.uaa.UaaPlugin$1.run(UaaPlugin.java:85) at org.eclipse.core.internal.jobs.Worker.run(Worker.java:54) !SESSION 2012-11-23 15:15:21.833 ----------------------------------------------- eclipse.buildId=I20120608-1200 java.version=1.7.0_09 java.vendor=Oracle Corporation BootLoader constants: OS=linux, ARCH=x86_64, WS=gtk, NL=en_US Command-line arguments: -os linux -ws gtk -arch x86_64 !ENTRY org.eclipse.jface 2 0 2012-11-23 15:15:27.283 !MESSAGE Keybinding conflicts occurred. They may interfere with normal accelerator operation. !SUBENTRY 1 org.eclipse.jface 2 0 2012-11-23 15:15:27.283 !MESSAGE A conflict occurred for ALT+SHIFT+R: Binding(ALT+SHIFT+R, ParameterizedCommand(Command(oracle.eclipse.tools.common.services.ui.refactor.rename.command,Rename, Rename the selected text., Category(org.eclipse.jdt.ui.category.refactoring,Refactor - Java,Java Refactoring Actions,true), oracle.eclipse.tools.common.services.ui.refactor.internal.ArtifactRefactoringCommandHandler, ,,true),null), org.eclipse.ui.defaultAcceleratorConfiguration, org.eclipse.ui.contexts.window,,,system) Binding(ALT+SHIFT+R, ParameterizedCommand(Command(org.eclipse.jdt.ui.edit.text.java.rename.element,Rename - Refactoring , Rename the selected element, Category(org.eclipse.jdt.ui.category.refactoring,Refactor - Java,Java Refactoring Actions,true), , ,,true),null), org.eclipse.ui.defaultAcceleratorConfiguration, org.eclipse.ui.contexts.window,,,system) !ENTRY org.eclipse.jface 2 0 2012-11-23 15:18:41.265 !MESSAGE Keybinding conflicts occurred. They may interfere with normal accelerator operation. !SUBENTRY 1 org.eclipse.jface 2 0 2012-11-23 15:18:41.265 !MESSAGE A conflict occurred for ALT+SHIFT+E: Binding(ALT+SHIFT+E, ParameterizedCommand(Command(oracle.eclipse.tools.common.services.ui.refactor.rename.command,Rename, Rename the selected text., Category(org.eclipse.jdt.ui.category.refactoring,Refactor - Java,Java Refactoring Actions,true), oracle.eclipse.tools.common.services.ui.refactor.internal.ArtifactRefactoringCommandHandler, ,,true),null), org.eclipse.ui.emacsAcceleratorConfiguration, org.eclipse.ui.contexts.window,,,user) Binding(ALT+SHIFT+E, ParameterizedCommand(Command(org.eclipse.jdt.ui.edit.text.java.rename.element,Rename - Refactoring , Rename the selected element, Category(org.eclipse.jdt.ui.category.refactoring,Refactor - Java,Java Refactoring Actions,true), , ,,true),null), org.eclipse.ui.emacsAcceleratorConfiguration, org.eclipse.ui.contexts.window,,,user) Binding(ALT+SHIFT+E, ParameterizedCommand(Command(org.eclipse.wst.jsdt.ui.edit.text.java.rename.element,Rename - Refactoring , Rename the selected element, Category(org.eclipse.wst.jsdt.ui.category.refactoring,Refactor - JavaScript,JavaScript Refactoring Actions,true), , ,,true),null), org.eclipse.ui.emacsAcceleratorConfiguration, org.eclipse.ui.contexts.window,,,user) !SESSION 2012-11-23 15:18:56.267 ----------------------------------------------- eclipse.buildId=I20120608-1200 java.version=1.7.0_09 java.vendor=Oracle Corporation BootLoader constants: OS=linux, ARCH=x86_64, WS=gtk, NL=en_US Command-line arguments: -os linux -ws gtk -arch x86_64 !ENTRY org.eclipse.jface 2 0 2012-11-23 15:19:01.605 !MESSAGE Keybinding conflicts occurred. They may interfere with normal accelerator operation. !SUBENTRY 1 org.eclipse.jface 2 0 2012-11-23 15:19:01.605 !MESSAGE A conflict occurred for ALT+SHIFT+E: Binding(ALT+SHIFT+E, ParameterizedCommand(Command(org.eclipse.wst.jsdt.ui.edit.text.java.rename.element,Rename - Refactoring , Rename the selected element, Category(org.eclipse.wst.jsdt.ui.category.refactoring,Refactor - JavaScript,JavaScript Refactoring Actions,true), , ,,true),null), org.eclipse.ui.emacsAcceleratorConfiguration, org.eclipse.ui.contexts.window,,,user) Binding(ALT+SHIFT+E, ParameterizedCommand(Command(org.eclipse.jdt.ui.edit.text.java.rename.element,Rename - Refactoring , Rename the selected element, Category(org.eclipse.jdt.ui.category.refactoring,Refactor - Java,Java Refactoring Actions,true), , ,,true),null), org.eclipse.ui.emacsAcceleratorConfiguration, org.eclipse.ui.contexts.window,,,user) Binding(ALT+SHIFT+E, ParameterizedCommand(Command(oracle.eclipse.tools.common.services.ui.refactor.rename.command,Rename, Rename the selected text., Category(org.eclipse.jdt.ui.category.refactoring,Refactor - Java,Java Refactoring Actions,true), oracle.eclipse.tools.common.services.ui.refactor.internal.ArtifactRefactoringCommandHandler, ,,true),null), org.eclipse.ui.emacsAcceleratorConfiguration, org.eclipse.ui.contexts.window,,,user)

    Read the article

  • how to use jquery autocomplete?

    - by kyrogue
    hi, i am creating a web project using JSP, and is trying to implement a simple search for users from my database using jquery autocomplete, however i am having trouble understanding how it works. i have little to no knowledge on jquery and ajax just to let you know. i have done the following code and am stuck. <%@page contentType="text/html" pageEncoding="UTF-8" import="ewa.dbConnect,ewa.sendEmail,ewa.pwGen,ewa.hashPw,java.sql.*" %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <link rel="stylesheet" type="text/css" href="css/jquery.autocomplete.css" /> <script src="js/jquery.autocomplete.js"></script> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>JSP Page</title> </head> <body> <input type="text" id="search" name="search"/> <script> $("#search").autocomplete("getdata.jsp"); </script> </body> </html> <%@page contentType="text/html" pageEncoding="UTF-8" import="ewa.dbConnect,java.sql.*" %> <%! dbConnect db = new dbConnect(); %> <% String query = request.getParameter("q"); db.connect(); Statement stmt = db.getConnection().createStatement(); ResultSet rs = stmt.executeQuery("SELECT username FROM created_accounts WHERE username LIKE "+query); while(rs.next()) { out.println(rs.getString("username")); } db.disconnect %> if i am not wrong i read from a website, the parameter q is default and is just there, however how do i display the data? how do i pass the values from getdata.jsp into the autocomplete?

    Read the article

  • Jquery autocomplete not firing on keyup unless focus changes

    - by TheIG
    I am using a jquery autocomplete and i have a keyup event for my textbox. When I enter in a letter the function is called but the box is not populated. Once I click away from the box and then click back into it the autocomplete works great. Really weird issue and I have no idea how to fix it. Any help would be appreciated. here's my code $(document).ready(function(){ var x; var output; x = document.getElementById('site').value; $.getJSON(url,{field: "name",value: x, comparison: "LIKE"}, function(json){ //code to format output $("#site").autocomplete(output, json); }); }); <input type ="text" size ="40" id="site"></input>

    Read the article

  • Bind jQuery UI autocomplete using .live()

    - by seth.vargo
    I've searched everywhere, but I can't seem to find any help... I have some textboxes that are created dynamically via JS, so I need to bind all of their classes to an autocomplete. As a result, I need to use the new .live() option. As an example, to bind all items with a class of .foo now and future created: $('.foo').live('click', function(){ alert('clicked'); }); It takes (and behaves) the same as .bind(). However, I want to bind an autocomplete... This doesn't work: $('.foo').live('autocomplete', function(event, ui){ source: 'url.php' // (surpressed other arguments) }); How can I use .live() to bind autocomplete? UPDATE Figured it out with Framer: $(function(){ $('.search').live('keyup.autocomplete', function(){ $(this).autocomplete({ source : 'url.php' }); }); });

    Read the article

1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >