Search Results

Search found 17309 results on 693 pages for 'jquery datepicker'.

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

  • How to change the cell color of a jquery datepicker

    - by MazarD
    Hi, I have a jquery datepicker and I need to be able to change the background color for the selected cell date, I'm trying with something like: $("#fecha").datepicker({ onSelect: function(value, date) { alert(date.css()); } }); hoping that the date parameter refers to the selected cell, but it doesn't seem to work. Any suggestion? //Edit: The solution should let me have different cells with different colors setted dinamically, this is why I'm trying with onSelect instead of changing the css directly. The purpose is to have a calender with events established by the user. Thanks in advance.

    Read the article

  • Enable Datepicker only when first field has a value

    - by Syed Abdul Rahman
    Right now, the End Date selection is disabled. I want to only enable this when a Start Date is selected. if( $('#datepicker1').val().length === 0) { $('#datepicker2').datepicker("disable"); } else { $('#datepicker2').datepicker("enable"); } This clearly does not work. If I insert value = 'random date' into my first input field, it works fine. I'm not too sure on how do this. Clearly not as easy as I had hoped. My other problem, or hope, is to disable the dates including and before the first selection. You know, pick Start Date, and every date before and said date for the next picker would be disabled. But that is a whole other problem.

    Read the article

  • JQuery datepicker

    - by showFocus
    Coud someone help me with this? I am getting these question marks in the graphic and i'm not sure why? I have seen these symbols before and i am sure it had something to do with charset. I am using: <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> Here is my JQuery code <script type="text/javascript"> $(function() { var date = $('#date').datepicker({ minDate: 0, dateFormat: "dd/mm/yy", beforeShowDay: function(date){ if (date.getDay() == 0){ return [false, '']; } else { return [true, '']; } } } ); }); </script> Image can be found here: http://kevinhenney.com/jquery-datepicker.jpg Tried to add an imaghe in the post, not allowed just yet. Thanks in advance

    Read the article

  • datepicker value is blank when disabled, jquery

    - by Mithil Deshmukh
    Hi. I'm fairly new to jQuery. I have a Jquery datepicker in a user control. I have added a "disable" property to the datepicker. Whenever I save the page(having this usercontrol) the datepicker with disable set to true is empty. All other datepickers save fine. Here is my code. ASPX < USERCONTROL:DATEPICKER id="dpBirthDate" startyear="1980" runat="server" Disable=true ASCX < input type="text" size="8" runat="server" id="txtDate" name="txtDate" onblur="ValidateForm(this.id);" / ASCX Code Behind Public Property Disable() As Boolean Get Return (txtDate.Disabled = True) End Get Set(ByVal bValue As Boolean) If (bValue = True) Then txtDate.Attributes.Add("Disabled", "True") Else txtDate.Attributes.Remove("Disabled") End If End Set End Property My Jquery $(document).ready(function() { $("input[id$=txtDate]").datepicker({ showOn: 'button', buttonImage: '<%=ConfigurationSettings.AppSettings("BASE_DIRECTORY")%>/Images/el-calendar.gif', buttonImageOnly: true }); $("input[id$=txtDate]").mask("99/99/9999", { placeholder: " " }); //Disable datepicker if "disable=true" $("input[id$=txtDate]").each(function() { if ($("input[id$=" + this.id + "]").attr("Disabled") == "True") { $("input[id$=" + this.id + "]").datepicker("disable"); } else if ($("input[id$=" + this.id + "]").attr("Disabled") == "False") { $("input[id$=" + this.id + "]").datepicker("enable"); } }); }); I am sorry, I am not sure how to format the code here. I apologies for the cluttered code. Can anybody tell me why the datepicker value is empty when it is disabled but works fine otherwise? Thanks is advance.

    Read the article

  • jQuery UI datepicker options as varialbe

    - by Desmond Liang
    I have a number of inputs on a page function as JQ UI datepicker. Each needs to have different settings. I want to minimize the JS so I save the settings as an attribute in each individual . <input type="text" class="datepicker" name="dateofbirth" id="dateofbirth" size="20" value="" options="{ dateFormat: 'yy-mm-dd',changeYear: true,yearRange: '1920:2010'}" /> <input type="text" class="datepicker" name="expdate" id="expdate" size="20" value="" options="{ yearRange: '2011:2020'}" /> I use js to load the options dynamically as the settings. $(document).ready(function(){ $(".datepicker").each(function(index){ $(this).datepicker("option" , $(this).attr('options')); }); }); datepicker is not functioning. If I empty the parentheses after $this.datepicker it works fine. I have also tried another way to assign settings. ("option",...) no dice.

    Read the article

  • jQuery DatePicker UI regional

    - by ScG
    I am aware that we can localize datepicker using $(selector).datepicker($.datepicker.regional['fr']); However can we do something like if a user passes in a value that's not supported by the datepicker regional, then automatically shift to the default language Something like: if(datepicker.regional does not support the language) $.datepicker.setDefaults($.datepicker.regional['']);

    Read the article

  • jQuery attribute selector inside a jQuery object

    - by chifliiiii
    Im trying to set up a quicksand with multiple filters and the approach im taking in the following which im not sure if its the best. $filteredItems = $containerClone.find('.portfolio-item-marketing').filter(function(index){ if ( $filterA != 'all' && $filterB != 'all' ) { return jQuery(this).find('.portfolio-item-marketing[data-type~=' + $filterA + ']') || jQuery(this).find('.portfolio-item-marketing[data-type~=' + $filterB + ']'); } if ( $filterA != 'all' && $filterB == 'all' ) { return jQuery(this+'[data-type~='+$filterA+']') ; } if ( $filterA == 'all' && $filterB != 'all' ) { return jQuery(this).find('.portfolio-item-marketing[data-type~=' + $filterB + ']'); } if ( $filterA == 'all' && $filterB == 'all' ) { return jQuery(this).find('.portfolio-item-marketing'); } }); As you see in the code i tried 2 different methods ( First "if" and second "if" ). Im not sure if i can use find inside a filter but i also dont know how to get the attribute from the jQuery object. I can not use jQuery(this).attr('data-type') == $filterA Because the attribute maybe contain various filters .Thats why im trying to use jQuery "~=" Should i give up and end using a indexOf ?

    Read the article

  • Make input field jquery ui datepicker editable

    - by Sam Vloeberghs
    Hi Folks, I've scanned trough the documentation but I can't find out how I to get the field to get the datepickers value AND let it be editable using my keyboard numpad. So filling/editing the date without using the datepicker. I hope my question is clear cause I don't know how the formulate it otherwise.. Greetings

    Read the article

  • Plugin jQuery da Microsoft para Globalização

    - by Leniel Macaferi
    No mês passado eu escrevi sobre como a Microsoft está começando a fazer contribuições de código para a jQuery (em Inglês), e sobre algumas das primeiras contribuições de código nas quais estávamos trabalhando: Suporte para Templates jQuery e Linkagem de Dados (em Inglês). Hoje, lançamos um protótipo de um novo plugin jQuery para Globalização que te permite adicionar suporte à globalização/internacionalização para as suas aplicações JavaScript. Este plugin inclui informações de globalização para mais de 350 culturas que vão desde o Gaélico Escocês, o Frísio, Húngaro, Japonês, e Inglês Canadense. Nós estaremos lançando este plugin para a comunidade em um formato de código livre. Você pode baixar nosso protótipo do plugin jQuery para Globalização a partir do nosso repositório Github: http://github.com/nje/jquery-glob Você também pode baixar um conjunto de exemplos que demonstram alguns simples casos de uso com ele aqui. Entendendo Globalização O plugin jQuery para Globalização permite que você facilmente analise e formate números, moedas e datas para diferentes culturas em JavaScript. Por exemplo, você pode usar o plugin de globalização para mostrar o símbolo da moeda adequado para uma cultura: Você também pode usar o plugin de globalização para formatar datas para que o dia e o mês apareçam na ordem certa e para que os nomes dos dias e meses sejam corretamente traduzidos: Observe acima como o ano Árabe é exibido como 1431. Isso ocorre porque o ano foi convertido para usar o calendário Árabe. Algumas diferenças culturais, tais como moeda diferente ou nomes de meses, são óbvias. Outras diferenças culturais são surpreendentes e sutis. Por exemplo, em algumas culturas, o agrupamento de números é feito de forma irregular. Na cultura "te-IN" (Telugu na Índia), grupos possuem 3 dígitos e, em seguida, dois dígitos. O número 1000000 (um milhão) é escrito como "10,00,000". Algumas culturas não agrupam os números. Todas essas sutis diferenças culturais são tratadas pelo plugin de Globalização da jQuery automaticamente. Pegar as datas corretamente pode ser especialmente complicado. Diferentes culturas têm calendários diferentes, como o Gregoriano e os calendários UmAlQura. Uma única cultura pode até mesmo ter vários calendários. Por exemplo, a cultura Japonesa usa o calendário Gregoriano e um calendário Japonês que possui eras com nomes de imperadores Japoneses. O plugin de Globalização inclui métodos para a conversão de datas entre todos estes diferentes calendários. Usando Tags de Idioma O plugin de Globalização da jQuery utiliza as tags de idioma definidas nos padrões das RFCs 4646 e 5646 para identificar culturas (veja http://tools.ietf.org/html/rfc5646). Uma tag de idioma é composta por uma ou mais subtags separadas por hífens. Por exemplo: Tag do Idioma Nome do Idioma (em Inglês) en-UA English (Australia) en-BZ English (Belize) en-CA English (Canada) Id Indonesian zh-CHS Chinese (Simplified) Legacy Zu isiZulu Observe que um único idioma, como o Inglês, pode ter várias tags de idioma. Falantes de Inglês no Canadá formatam números, moedas e datas usando diferentes convenções daquelas usadas pelos falantes de Inglês na Austrália ou nos Estados Unidos. Você pode encontrar a tag de idioma para uma cultura específica usando a Language Subtag Lookup Tool (Ferramenta de Pesquisa de Subtags de Idiomas) em: http://rishida.net/utils/subtags/ O download do plugin de Globalização da jQuery inclui uma pasta chamada globinfo que contém as informações de cada uma das 350 culturas. Na verdade, esta pasta contém mais de 700 arquivos, porque a pasta inclui ambas as versões minified (tamanho reduzido) e não-minified de cada arquivo. Por exemplo, a pasta globinfo inclui arquivos JavaScript chamados jQuery.glob.en-AU.js para o Inglês da Austrália, jQuery.glob.id.js para o Indonésio, e jQuery.glob.zh-CHS para o Chinês (simplificado) Legacy. Exemplo: Definindo uma Cultura Específica Imagine que te pediram para criar um site em Alemão e que querem formatar todas as datas, moedas e números usando convenções de formatação da cultura Alemã de maneira correta em JavaScript no lado do cliente. O código HTML para a página pode ser igual a este: Observe as tags span acima. Elas marcam as áreas da página que desejamos formatar com o plugin de Globalização. Queremos formatar o preço do produto, a data em que o produto está disponível, e as unidades do produto em estoque. Para usar o plugin de Globalização da jQuery, vamos adicionar três arquivos JavaScript na página: a biblioteca jQuery, o plugin de Globalização da jQuery, e as informações de cultura para um determinado idioma: Neste caso, eu estaticamente acrescentei o arquivo JavaScript jQuery.glob.de-DE.js que contém as informações para a cultura Alemã. A tag de idioma "de-DE" é usada para o Alemão falado na Alemanha. Agora que eu tenho todos os scripts necessários, eu posso usar o plugin de Globalização para formatar os valores do preço do produto, data disponível, e unidades no estoque usando o seguinte JavaScript no lado do cliente: O plugin de Globalização jQuery amplia a biblioteca jQuery com novos métodos - incluindo novos métodos chamados preferCulture() e format(). O método preferCulture() permite que você defina a cultura padrão utilizada pelos métodos do plugin de Globalização da jQuery. Observe que o método preferCulture() aceita uma tag de idioma. O método irá buscar a cultura mais próxima que corresponda à tag do idioma. O método $.format() é usado para formatar os valores monetários, datas e números. O segundo parâmetro passado para o método $.format() é um especificador de formato. Por exemplo, passar um "c" faz com que o valor seja formatado como moeda. O arquivo LeiaMe (ReadMe) no github detalha o significado de todos os diferentes especificadores de formato: http://github.com/nje/jquery-glob Quando abrimos a página em um navegador, tudo está formatado corretamente de acordo com as convenções da língua Alemã. Um símbolo do euro é usado para o símbolo de moeda. A data é formatada usando nomes de dia e mês em Alemão. Finalmente, um ponto, em vez de uma vírgula é usado como separador numérico: Você pode ver um exemplo em execução da abordagem acima com o arquivo 3_GermanSite.htm neste download de amostras. Exemplo: Permitindo que um Usuário Selecione Dinamicamente uma Cultura No exemplo anterior, nós explicitamente dissemos que queríamos globalizar em Alemão (referenciando o arquivo jQuery.glob.de-DE.js). Vamos agora olhar para o primeiro de alguns exemplos que demonstram como definir dinamicamente a cultura da globalização a ser usada. Imagine que você deseja exibir uma lista suspensa (dropdown) de todas as 350 culturas em uma página. Quando alguém escolhe uma cultura a partir da lista suspensa, você quer que todas as datas da página sejam formatadas usando a cultura selecionada. Aqui está o código HTML para a página: Observe que todas as datas estão contidas em uma tag <span> com um atributo data-date (atributos data-* são um novo recurso da HTML 5, que convenientemente também ainda funcionam com navegadores mais antigos). Nós vamos formatar a data representada pelo atributo data-date quando um usuário selecionar uma cultura a partir da lista suspensa. A fim de mostrar as datas para qualquer cultura disponível, vamos incluir o arquivo jQuery.glob.all.js igual a seguir: O plugin de Globalização da jQuery inclui um arquivo JavaScript chamado jQuery.glob.all.js. Este arquivo contém informações de globalização para todas as mais de 350 culturas suportadas pelo plugin de Globalização. Em um tamanho de 367 KB minified (reduzido), esse arquivo não é pequeno. Devido ao tamanho deste arquivo, a menos que você realmente precise usar todas essas culturas, ao mesmo tempo, recomendamos que você adicione em uma página somente os arquivos JavaScript individuais para as culturas específicas que você pretende suportar, ao invés do arquivo jQuery.glob.all.js combinado. No próximo exemplo, eu vou mostrar como carregar dinamicamente apenas os arquivos de idioma que você precisa. A seguir, vamos preencher a lista suspensa com todas as culturas disponíveis. Podemos usar a propriedade $.cultures para obter todas as culturas carregadas: Finalmente, vamos escrever o código jQuery que pega cada elemento span com um atributo data-date e formataremos a data: O método parseDate() do plugin de Globalização da jQuery é usado para converter uma representação de uma data em string para uma data JavaScript. O método format() do plugin é usado para formatar a data. O especificador de formato "D" faz com que a data a ser formatada use o formato de data longa. E agora, o conteúdo será globalizado corretamente, independentemente de qual das 350 línguas o usuário que visita a página selecione. Você pode ver um exemplo em execução da abordagem acima com o arquivo 4_SelectCulture.htm neste download de amostras. Exemplo: Carregando Arquivos de Globalização Dinamicamente Conforme mencionado na seção anterior, você deve evitar adicionar o arquivo jQuery.glob.all.js em uma página, sempre que possível, porque o arquivo é muito grande. Uma melhor alternativa é carregar as informações de globalização que você precisa dinamicamente. Por exemplo, imagine que você tenha criado uma lista suspensa que exibe uma lista de idiomas: O seguinte código jQuery é executado sempre que um usuário seleciona um novo idioma na lista suspensa. O código verifica se o arquivo associado com a globalização do idioma selecionado já foi carregado. Se o arquivo de globalização ainda não foi carregado, o arquivo de globalização é carregado dinamicamente, tirando vantagem do método $.getScript() da jQuery. O método globalizePage() é chamado depois que o arquivo de globalização solicitado tenha sido carregado, e contém o código do lado do cliente necessário para realizar a globalização. A vantagem dessa abordagem é que ela permite evitar o carregamento do arquivo jQuery.glob.all.js inteiro. Em vez disso você só precisa carregar os arquivos que você vai usar e você não precisa carregar os arquivos mais de uma vez. O arquivo 5_Dynamic.htm neste download de amostras demonstra como implementar esta abordagem. Exemplo: Definindo o Idioma Preferido do Usuário Automaticamente Muitos sites detectam o idioma preferido do usuário a partir das configurações de seu navegador e as usam automaticamente quando globalizam o conteúdo. Um usuário pode definir o idioma preferido para o seu navegador. Então, sempre que o usuário solicita uma página, esta preferência de idioma está incluída no pedido no cabeçalho Accept-Language. Quando você usa o Microsoft Internet Explorer, você pode definir o seu idioma preferido, seguindo estes passos: Selecione a opção do menu Ferramentas, Opções da Internet. Selecione a guia/tab Geral. Clique no botão Idiomas na seção Aparência. Clique no botão Adicionar para adicionar um novo idioma na lista de idiomas. Mova seu idioma preferido para o topo da lista. Observe que você pode listar múltiplos idiomas na janela de diálogo de Preferências de Idioma. Todas estas línguas são enviadas na ordem em que você as listou no cabeçalho Accept-Language: Accept-Language: fr-FR,id-ID;q=0.7,en-US;q= 0.3 Estranhamente, você não pode recuperar o valor do cabeçalho Accept-Language a partir do código JavaScript no lado do cliente. O Microsoft Internet Explorer e o Mozilla Firefox suportam um grupo de propriedades relacionadas a idiomas que são expostas pelo objeto window.navigator, tais como windows.navigator.browserLanguage e window.navigator.language, mas essas propriedades representam tanto o idioma definido para o sistema operacional ou a linguagem de edição do navegador. Essas propriedades não permitem que você recupere o idioma que o usuário definiu como seu idioma preferido. A única maneira confiável para se obter o idioma preferido do usuário (o valor do cabeçalho Accept-Language) é escrever código no lado do servidor. Por exemplo, a seguinte página ASP.NET tira vantagem da propriedade do servidor Request.UserLanguages para atribuir o idioma preferido do usuário para uma variável JavaScript no lado do cliente chamada AcceptLanguage (a qual então permite que você acesse o valor usando código JavaScript no lado do cliente): Para que este código funcione, as informações de cultura associadas ao valor de acceptLanguage devem ser incluídas na página. Por exemplo, se a cultura preferida de alguém é fr-FR (Francês na França) então você precisa incluir tanto o arquivo jQuery.glob.fr-FR.js ou o arquivo jQuery.glob.all.js na página; caso contrário, as informações de cultura não estarão disponíveis. O exemplo "6_AcceptLanguages.aspx" neste download de amostras demonstra como implementar esta abordagem. Se as informações de cultura para o idioma preferido do usuário não estiverem incluídas na página, então, o método $.preferCulture() voltará a usar a cultura neutra (por exemplo, passará a usar jQuery.glob.fr.js ao invés de jQuery.glob.fr-FR.js). Se as informações da cultura neutra não estiverem disponíveis, então, o método $.preferCulture() retornará para a cultura padrão (Inglês). Exemplo: Usando o Plugin de Globalização com o jQuery UI DatePicker (Selecionador de Datas da jQuery) Um dos objetivos do plugin de Globalização é tornar mais fácil construir widgets jQuery que podem ser usados com diferentes culturas. Nós queríamos ter certeza de que o plugin de Globalização da jQuery pudesse funcionar com os plugins de UI (interface do usuário) da jQuery, como o plugin DatePicker. Para esse fim, criamos uma versão corrigida do plugin DatePicker que pode tirar proveito do plugin de Globalização na renderização de um calendário. A imagem a seguir ilustra o que acontece quando você adiciona o plugin de Globalização jQuery e o plugin DatePicker da jQuery corrigido em uma página e seleciona a cultura da Indonésia como preferencial: Note que os cabeçalhos para os dias da semana são exibidos usando abreviaturas dos nomes dos dias referentes ao idioma Indonésio. Além disso, os nomes dos meses são exibidos em Indonésio. Você pode baixar a versão corrigida do jQuery UI DatePicker no nosso site no github. Ou você pode usar a versão incluída neste download de amostras e usada pelo arquivo de exemplo 7_DatePicker.htm. Sumário Estou animado com a nossa participação contínua na comunidade jQuery. Este plugin de Globalização é o terceiro plugin jQuery que lançamos. Nós realmente apreciamos todos os ótimos comentários e sugestões sobre os protótipos do Suporte para Templates jQuery e Linkagem de Dados que lançamos mais cedo neste ano. Queremos também agradecer aos times da jQuery e jQuery UI por trabalharem conosco na criação deses plugins. Espero que isso ajude, Scott P.S. Além do blog, eu também estou agora utilizando o Twitter para atualizações rápidas e para compartilhar links. Você pode me acompanhar em: twitter.com/scottgu   Texto traduzido do post original por Leniel Macaferi.

    Read the article

  • jqueryui datepicker customize problem

    - by niao
    Greeting, I would like the jqueryui datapicker to use polish localization. Additionally, the dates have to be limited so it should not be possible to choose past dates. I have something like this: $.datepicker.setDefaults($.datepicker.regional['pl']); $("#StartDate").datepicker({ minDate: 0, maxDate: '+1Y ' }); $("#StartDate").datepicker('option', $.datepicker.regional['pl']); Limitation works find, but I cannot achieve polish localization. Please help.

    Read the article

  • jquery nested sortable

    - by mcgrailm
    I have been using NestedSortabe from b-hind and found it quite useful until I upgraded to latest jquery and jquery-ui I guess they changed the way mouse events are handled or something to that effect. Point it the nestedSortable doesn't work any longer. So my question is tri fold does anyone know if the folks at jquery have implemented a nested sortable I haven't seen anything. or does anyone know how to fix the b-hind version or know of something better / light weight to accomplish the same goals would like something compatible with lastest jquery-ui EDIT: it appears as though the lastest version of jquery-ui-sortable supports nested sorting !!!

    Read the article

  • jQuery Globalization Plugin from Microsoft

    - by ScottGu
    Last month I blogged about how Microsoft is starting to make code contributions to jQuery, and about some of the first code contributions we were working on: jQuery Templates and Data Linking support. Today, we released a prototype of a new jQuery Globalization Plugin that enables you to add globalization support to your JavaScript applications. This plugin includes globalization information for over 350 cultures ranging from Scottish Gaelic, Frisian, Hungarian, Japanese, to Canadian English.  We will be releasing this plugin to the community as open-source. You can download our prototype for the jQuery Globalization plugin from our Github repository: http://github.com/nje/jquery-glob You can also download a set of samples that demonstrate some simple use-cases with it here. Understanding Globalization The jQuery Globalization plugin enables you to easily parse and format numbers, currencies, and dates for different cultures in JavaScript. For example, you can use the Globalization plugin to display the proper currency symbol for a culture: You also can use the Globalization plugin to format dates so that the day and month appear in the right order and the day and month names are correctly translated: Notice above how the Arabic year is displayed as 1431. This is because the year has been converted to use the Arabic calendar. Some cultural differences, such as different currency or different month names, are obvious. Other cultural differences are surprising and subtle. For example, in some cultures, the grouping of numbers is done unevenly. In the "te-IN" culture (Telugu in India), groups have 3 digits and then 2 digits. The number 1000000 (one million) is written as "10,00,000". Some cultures do not group numbers at all. All of these subtle cultural differences are handled by the jQuery Globalization plugin automatically. Getting dates right can be especially tricky. Different cultures have different calendars such as the Gregorian and UmAlQura calendars. A single culture can even have multiple calendars. For example, the Japanese culture uses both the Gregorian calendar and a Japanese calendar that has eras named after Japanese emperors. The Globalization Plugin includes methods for converting dates between all of these different calendars. Using Language Tags The jQuery Globalization plugin uses the language tags defined in the RFC 4646 and RFC 5646 standards to identity cultures (see http://tools.ietf.org/html/rfc5646). A language tag is composed out of one or more subtags separated by hyphens. For example: Language Tag Language Name (in English) en-AU English (Australia) en-BZ English (Belize) en-CA English (Canada) Id Indonesian zh-CHS Chinese (Simplified) Legacy Zu isiZulu Notice that a single language, such as English, can have several language tags. Speakers of English in Canada format numbers, currencies, and dates using different conventions than speakers of English in Australia or the United States. You can find the language tag for a particular culture by using the Language Subtag Lookup tool located here:  http://rishida.net/utils/subtags/ The jQuery Globalization plugin download includes a folder named globinfo that contains the information for each of the 350 cultures. Actually, this folder contains more than 700 files because the folder includes both minified and un-minified versions of each file. For example, the globinfo folder includes JavaScript files named jQuery.glob.en-AU.js for English Australia, jQuery.glob.id.js for Indonesia, and jQuery.glob.zh-CHS for Chinese (Simplified) Legacy. Example: Setting a Particular Culture Imagine that you have been asked to create a German website and want to format all of the dates, currencies, and numbers using German formatting conventions correctly in JavaScript on the client. The HTML for the page might look like this: Notice the span tags above. They mark the areas of the page that we want to format with the Globalization plugin. We want to format the product price, the date the product is available, and the units of the product in stock. To use the jQuery Globalization plugin, we’ll add three JavaScript files to the page: the jQuery library, the jQuery Globalization plugin, and the culture information for a particular language: In this case, I’ve statically added the jQuery.glob.de-DE.js JavaScript file that contains the culture information for German. The language tag “de-DE” is used for German as spoken in Germany. Now that I have all of the necessary scripts, I can use the Globalization plugin to format the product price, date available, and units in stock values using the following client-side JavaScript: The jQuery Globalization plugin extends the jQuery library with new methods - including new methods named preferCulture() and format(). The preferCulture() method enables you to set the default culture used by the jQuery Globalization plugin methods. Notice that the preferCulture() method accepts a language tag. The method will find the closest culture that matches the language tag. The $.format() method is used to actually format the currencies, dates, and numbers. The second parameter passed to the $.format() method is a format specifier. For example, passing “c” causes the value to be formatted as a currency. The ReadMe file at github details the meaning of all of the various format specifiers: http://github.com/nje/jquery-glob When we open the page in a browser, everything is formatted correctly according to German language conventions. A euro symbol is used for the currency symbol. The date is formatted using German day and month names. Finally, a period instead of a comma is used a number separator: You can see a running example of the above approach with the 3_GermanSite.htm file in this samples download. Example: Enabling a User to Dynamically Select a Culture In the previous example we explicitly said that we wanted to globalize in German (by referencing the jQuery.glob.de-DE.js file). Let’s now look at the first of a few examples that demonstrate how to dynamically set the globalization culture to use. Imagine that you want to display a dropdown list of all of the 350 cultures in a page. When someone selects a culture from the dropdown list, you want all of the dates in the page to be formatted using the selected culture. Here’s the HTML for the page: Notice that all of the dates are contained in a <span> tag with a data-date attribute (data-* attributes are a new feature of HTML 5 that conveniently also still work with older browsers). We’ll format the date represented by the data-date attribute when a user selects a culture from the dropdown list. In order to display dates for any possible culture, we’ll include the jQuery.glob.all.js file like this: The jQuery Globalization plugin includes a JavaScript file named jQuery.glob.all.js. This file contains globalization information for all of the more than 350 cultures supported by the Globalization plugin.  At 367KB minified, this file is not small. Because of the size of this file, unless you really need to use all of these cultures at the same time, we recommend that you add the individual JavaScript files for particular cultures that you intend to support instead of the combined jQuery.glob.all.js to a page. In the next sample I’ll show how to dynamically load just the language files you need. Next, we’ll populate the dropdown list with all of the available cultures. We can use the $.cultures property to get all of the loaded cultures: Finally, we’ll write jQuery code that grabs every span element with a data-date attribute and format the date: The jQuery Globalization plugin’s parseDate() method is used to convert a string representation of a date into a JavaScript date. The plugin’s format() method is used to format the date. The “D” format specifier causes the date to be formatted using the long date format. And now the content will be globalized correctly regardless of which of the 350 languages a user visiting the page selects.  You can see a running example of the above approach with the 4_SelectCulture.htm file in this samples download. Example: Loading Globalization Files Dynamically As mentioned in the previous section, you should avoid adding the jQuery.glob.all.js file to a page whenever possible because the file is so large. A better alternative is to load the globalization information that you need dynamically. For example, imagine that you have created a dropdown list that displays a list of languages: The following jQuery code executes whenever a user selects a new language from the dropdown list. The code checks whether the globalization file associated with the selected language has already been loaded. If the globalization file has not been loaded then the globalization file is loaded dynamically by taking advantage of the jQuery $.getScript() method. The globalizePage() method is called after the requested globalization file has been loaded, and contains the client-side code to perform the globalization. The advantage of this approach is that it enables you to avoid loading the entire jQuery.glob.all.js file. Instead you only need to load the files that you need and you don’t need to load the files more than once. The 5_Dynamic.htm file in this samples download demonstrates how to implement this approach. Example: Setting the User Preferred Language Automatically Many websites detect a user’s preferred language from their browser settings and automatically use it when globalizing content. A user can set a preferred language for their browser. Then, whenever the user requests a page, this language preference is included in the request in the Accept-Language header. When using Microsoft Internet Explorer, you can set your preferred language by following these steps: Select the menu option Tools, Internet Options. Select the General tab. Click the Languages button in the Appearance section. Click the Add button to add a new language to the list of languages. Move your preferred language to the top of the list. Notice that you can list multiple languages in the Language Preference dialog. All of these languages are sent in the order that you listed them in the Accept-Language header: Accept-Language: fr-FR,id-ID;q=0.7,en-US;q=0.3 Strangely, you cannot retrieve the value of the Accept-Language header from client JavaScript. Microsoft Internet Explorer and Mozilla Firefox support a bevy of language related properties exposed by the window.navigator object, such as windows.navigator.browserLanguage and window.navigator.language, but these properties represent either the language set for the operating system or the language edition of the browser. These properties don’t enable you to retrieve the language that the user set as his or her preferred language. The only reliable way to get a user’s preferred language (the value of the Accept-Language header) is to write server code. For example, the following ASP.NET page takes advantage of the server Request.UserLanguages property to assign the user’s preferred language to a client JavaScript variable named acceptLanguage (which then allows you to access the value using client-side JavaScript): In order for this code to work, the culture information associated with the value of acceptLanguage must be included in the page. For example, if someone’s preferred culture is fr-FR (French in France) then you need to include either the jQuery.glob.fr-FR.js or the jQuery.glob.all.js JavaScript file in the page or the culture information won’t be available.  The “6_AcceptLanguages.aspx” sample in this samples download demonstrates how to implement this approach. If the culture information for the user’s preferred language is not included in the page then the $.preferCulture() method will fall back to using the neutral culture (for example, using jQuery.glob.fr.js instead of jQuery.glob.fr-FR.js). If the neutral culture information is not available then the $.preferCulture() method falls back to the default culture (English). Example: Using the Globalization Plugin with the jQuery UI DatePicker One of the goals of the Globalization plugin is to make it easier to build jQuery widgets that can be used with different cultures. We wanted to make sure that the jQuery Globalization plugin could work with existing jQuery UI plugins such as the DatePicker plugin. To that end, we created a patched version of the DatePicker plugin that can take advantage of the Globalization plugin when rendering a calendar. For example, the following figure illustrates what happens when you add the jQuery Globalization and the patched jQuery UI DatePicker plugin to a page and select Indonesian as the preferred culture: Notice that the headers for the days of the week are displayed using Indonesian day name abbreviations. Furthermore, the month names are displayed in Indonesian. You can download the patched version of the jQuery UI DatePicker from our github website. Or you can use the version included in this samples download and used by the 7_DatePicker.htm sample file. Summary I’m excited about our continuing participation in the jQuery community. This Globalization plugin is the third jQuery plugin that we’ve released. We’ve really appreciated all of the great feedback and design suggestions on the jQuery templating and data-linking prototypes that we released earlier this year.  We also want to thank the jQuery and jQuery UI teams for working with us to create these plugins. Hope this helps, Scott P.S. In addition to blogging, I am also now using Twitter for quick updates and to share links. You can follow me at: twitter.com/scottgu

    Read the article

  • problem when cloning jQuery UI datepicker

    - by h3
    I have a div in which there is a datepicker. I use something like this to clone it: mydiv = $('#someDiv'); // works fine so far mydiv.find('input.datefield').datepicker(); // clone without the events and insert newDiv = myDiv.clone(false).insertAfter(myDiv); // datepicker won't re-init if this class is present newDiv.find('.hadDatepicker').removeClass('hadDatepicker'); // reinitialize datepicker newDiv.find('input.datefield').datepicker(); This is a stripped down version of my code. It works and the calendar shows up as expected where it is expected .. but when a date is clicked, the previous datepicker's value gets updated.. (the one from which it was cloned). I've tried to destroy the (inexisting) instance before like this: newDiv.find('input.datefield').datepicker('destroy').datepicker(); No luck .. I've checked how it keeps track of instances and manually cleared the data like this: newDiv.find('input.datefield').data('datepicker', false).datepicker('destroy').datepicker(); Still no luck. What I don't understand is that only the date selection behavior is buggy, everything else works as expected. I really don't know what else to check now ..

    Read the article

  • jQuery, jQuery UI, and Dual Licensed Plugins (Dual Licensing)

    - by John Hartsock
    OK I have read many posts regarding Dual Licensing using MIT and GPL licenses. But Im curious still, as the wording seems to be inclusive. Many of the Dual Licenses state that the software is licensed using "MIT AND GPL". The "AND" is what confuses me. It seems to me that the word "AND" in the terms, means you will be licensing the product using both licenses. Most of the posts, here on stackoverflow, state that you can license the software using one "OR" the other. JQuery specifically states "OR", whereas JQuery UI specifically States "AND". Another Instance of the "AND" would be JQGrid. Im not a lawyer but, it seems to me that a legal interpretation of this would state that use of the software would mean that your using the software under both licenses. Has anyone who has contacted a lawyer gotten clarification or a definitive answer as to what is true? Can you use Dual licensed software products that state "AND" in the terms of agreement under either license? EDITED: Guys here is specifically what Im talking about on jquery.org/license you see the following stated: You may use any jQuery project under the terms of either the MIT License or the GNU General Public License (GPL) Version 2 but in the header of Jquery's and Jquery UI library you see this: * Dual licensed under the MIT and GPL licenses. * http://docs.jquery.com/License The site says MIT or GPL but the license statement in the software says MIT and GPL.

    Read the article

  • jQuery Templates in ASP.NET - Blogs Series

    - by hajan
    In the previous days, I wrote several blog posts related to the great jQuery Templates plugin showing various examples that might help you get started working with the plugin in ASP.NET and VS.NET environment. Here is the list of all five blogs: Introduction to jQuery Templates jQuery Templates - tmpl(), template() and tmplItem() jQuery Templates - {Supported Tags} jQuery Templates with ASP.NET MVC jQuery Templates - XHTML Validation Thank you for reading and wait for my next blogs! All the best, Hajan

    Read the article

  • jQuery DatePicker - 'fake' click on page load

    - by Danny
    Hey! I've got a quick question about the jQuery UI DatePicker. When I load the page, defaultDate: 0 will work fine with selecting the current day's date. I would like to create a 'fake' click on the date so it will execute my JavaScript function and retrieve information from the database. I tried calling the function when the page loads but that doesn't work. $(document).ready(function(){ $("#datepicker").datepicker({ gotoCurrent: false, onSelect: function(date, inst) { ajaxFunction(date); }, dateFormat: 'dd-mm-yy', defaultDate: 0, changeMonth: true, changeYear: true }); }); //Browser Support Code function ajaxFunction(date){ var ajaxRequest; // The variable that makes Ajax possible! try{ // Opera 8.0+, Firefox, Safari ajaxRequest = new XMLHttpRequest(); } catch (e){ // Internet Explorer Browsers try{ ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try{ ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e){ // Something went wrong alert("Your browser broke!"); return false; } } } // Create a function that will receive data sent from the server ajaxRequest.onreadystatechange = function(){ if(ajaxRequest.readyState == 4){ var ajaxDisplay = document.getElementById('ajaxDiv'); ajaxDisplay.innerHTML = ajaxRequest.responseText; } } var queryString = "?date=" + date; ajaxRequest.open("GET", "getDiary.php" + queryString, true); ajaxRequest.send(null); } function ajaxAdd(){ var ajaxRequest; // The variable that makes Ajax possible! try{ // Opera 8.0+, Firefox, Safari ajaxRequest = new XMLHttpRequest(); } catch (e){ // Internet Explorer Browsers try{ ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try{ ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e){ // Something went wrong alert("Your browser broke!"); return false; } } } var day1 = $("#datepicker").datepicker('getDate').getDate(); var day2 = (day1 < 10) ? '0' + day1 : day1; var month1 = $("#datepicker").datepicker('getDate').getMonth() + 1; var month2 = (month1 < 10) ? '0' + month1 : month1; var year1 = $("#datepicker").datepicker('getDate').getFullYear(); var year2 = (year1 < 1000) ? year1 + 1900 : year1; var fullDate = day2 + "-" + month2 + "-" + year2; var queryString = "?breakfast=" + diary1.breakfast.value; queryString = queryString + "&lunch=" + diary1.lunch.value; queryString = queryString + "&dinner=" + diary1.dinner.value; queryString = queryString + "&date=" + fullDate; ajaxRequest.open("GET", "addDiary.php" + queryString, true); ajaxRequest.send(null); alert("Added value to database!"); diary1.breakfast.value = ""; diary1.lunch.value = ""; diary1.dinner.value = ""; ajaxFunction(fullDate); } I have pasted my DatePicker class, and the two functions that are used (one to retrieve information from the database, and one to store). Basically I want to mirror the onSelect: function on the DatePicker, but when the page first loads. Thanks!

    Read the article

  • jQuery validate plugin against custom jQueryUI datePickers

    - by Enrique
    I have some datePickers I've customized these so they show only month and year This is the code to create them jQuery("input[name*='fechauso']").each(function() { jQuery(this).datepicker({ changeMonth: true, changeYear: true, showButtonPanel: true, dateFormat: 'MM yy', constrainInput: true, showOn: 'button', buttonText: 'Seleccionar...', onClose: function(dateText, inst) { var month = jQuery("#ui-datepicker-div .ui-datepicker-month :selected").val(); var year = jQuery("#ui-datepicker-div .ui-datepicker-year :selected").val(); jQuery(this).datepicker('setDate', new Date(year, month, 1)); } }); }); Now I've added a custom validator method (using plugin) to check this: If user didn't select a date using the button, field is empty, so the custom validator method should fire. This doesn't happen. Here is the custom validate method jQuery.validator.addMethod("isEmpty", function(value, element) { return (value == ''); }, "Must select a date with the button besides control"); jQuery("#ct_2_fechauso").rules("add", { required: "#campotilde_psico:checked", isEmpty: true }); The problem is that even if I select a date, it always ask me to select a date again. datePicker fields should be readonly

    Read the article

  • How to use JQuery UI datepicker with bgIframe on IE 6

    - by Steve Davies
    I am trying to use the JQuery UI datepicker (latest stable version 1.5.2) on an IE6 website. But I am having the usual problems with combo boxes (selects) on IE6 where they float above other controls. I have tried adding the bgIframe plugin after declaring the datepicker with no luck. My guess is that the .ui-datepicker-div to which I am attaching the bgIframe doesn't exist until the calendar is shown. I am wondering if I can put the .bgIframe() command directly into the datepicker .js file and if so, where? (the similar control by kelvin Luck uses this approach) Current code $(".DateItem").datepicker({ showOn:"button", ... etc ... }); $(".ui-datepicker-div").bgIframe();

    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 Template textbox not showing datepicker

    - by pirzada
    I am using Datepicker on one of the the textbox in Jquery template but its not popping up. Outside of the template working fine. Below is what I want to do. jQuery().ready(function () { //$("#HireDate").datepicker(); $("#HireDate").datepicker({dateFormat:'dd-mm-yy', showAnim:'fadeIn'}) }); <script id="UserDetailTemplate" type="text/x-jquery-tmpl"> <table style="width:100%;"> <tbody> <tr> <td style="width:25%;font-weight:bold;">HireDate:</td> <td><input type="text" id="HireDate" value="${ HireDate }" /></td> </tr> </table> </td> </tr> </tbody> </table> </script>

    Read the article

  • jQuery datepicker years shown

    - by John Boker
    With the jQuery datepicker, how does one change the year range that is displayed? On the jQuery UI site it says the default is "10 years before and after the current year are shown". I want to use this for a birthday selection and 10 years before today is no good. Can this be done with the jQuery datepicker or will I have to use a different solution? link to datepicker demo: http://ui.jquery.com/repository/latest/demos/functional/#ui.datepicker

    Read the article

  • Ruby on Rails: jQuery datepicker - dates between validation

    - by Jazz
    I have an app that allows a user to create new projects, and the search for them later. One of the options they have when creating a project is giving them start and end dates. At the moment all the code works properly for creating and searching on the dates, but I am now wanting to restrict what dates the user can enter. I am needing for an error to flag up when the user tries to enter an end date that is before the start date. It's really more for when the user is creating the project. Here is my code so far = Application.js //= require jquery //= require jquery_ujs //= require jquery-ui //= require jquery.ui.all //= require_tree . $(function() { $("#project_start_date").datepicker({dateFormat: 'dd-mm-yy'}); }); $(function() { $("#project_end_date").datepicker({dateFormat: 'dd-mm-yy'}); }); jQuery(function(){ jQuery('#start_date_A').datepicker({dateFormat: "dd-mm-yy"}); }); jQuery(function(){ jQuery('#start_date_B').datepicker({dateFormat: "dd-mm-yy"}); }); New View: <div class="start_date" STYLE="text-align: left;"> <b>Start Date:</b> <%= f.text_field :start_date, :class => 'datepicker', :style => 'width: 80px;' %> </div> <div class="end_date" STYLE="text-align: left;"> <b>End Date:</b> <%= f.text_field :end_date, :class => 'datepicker', :style => 'width: 80px;' %> </div> Search View: Start dates between <%= text_field_tag :start_date_A, params[:start_date_A], :style => 'width: 80px;' %> - <%= text_field_tag :start_date_B, params[:start_date_B], :style => 'width: 80px;' %></br> I tried following examples online to get this to work by doing this in the application.js file: $(function() { $("#project_start_date,#project_end_date").datepicker({dateFormat: 'dd-mm-yy'}); }); jQuery(function(){ jQuery('#start_date_A,#start_date_B').datepicker({dateFormat: "dd-mm-yy"}); }); But then the script doesn't run. I am new to rails and javascript so any help at all is appreciated. Thanks in advance. UPDATE: Don't know why my question has been voted to be closed. It's quite simple: I need an error to flag up when the user tries to enter an end date that is before the start date. How can I do that??

    Read the article

  • JQuery Window blinking

    - by Nisanth
    Hi All I am developing a chat application(Customer and operator). Using jquery Ajax and PHP . From customer side he can handle multiple chat.. For example ha have two chat.. How he knows in which window the new msg comes.. I can take the count . But is there any option in jquery to blink the window when count change ?

    Read the article

  • JQuery Internals Documentation

    - by Steve
    Is there any documentation available that explains the internals of JQuery and JQuery UI? I have been looking through the source code, and while much of it makes sense, I was still hoping for an overview to help speed up my learning process. Thanks

    Read the article

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