Search Results

Search found 488 results on 20 pages for 'datepicker'.

Page 12/20 | < Previous Page | 8 9 10 11 12 13 14 15 16 17 18 19  | Next Page >

  • how to change a button into a imagebutton in asp.net c#

    - by sweetsecret
    How to change the button into image button... the button in the beginning has "Pick a date" when clicked a calender pops out and the when a date is selected a label at the bottom reading the date comes in and the text on the button changes to disabled... i want to palce a imagebutton having a image icon of the calender and rest of the function will be the same.... the code as follows: using System; using System.Collections.Generic; using System.ComponentModel; using System.Text; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; [assembly: TagPrefix("DatePicker", "EWS")] namespace EclipseWebSolutions.DatePicker { [DefaultProperty("Text")] [ToolboxData("<{0}:DatePicker runat=server")] [DefaultEvent("SelectionChanged")] [ValidationProperty("TextValue")] public class DatePicker : WebControl, INamingContainer { #region Properties public TextBox txtDate = new TextBox(); public Calendar calDate = new Calendar(); public Button btnDate = new Button(); public Panel pnlCalendar = new Panel(); private enum ViewStateConstants { ValidationGroup, RegularExpression, ErrorMessage, RegExText, CalendarPosition, FormatString, ExpandLabel, CollapseLabel, ApplyDefaultStyle, CausesValidation, } /// <summary> /// Defines the available display modes of this calendar. /// </summary> public enum CalendarDisplay { DisplayRight, DisplayBelow } /// <summary> /// Where to display the popup calendar. /// </summary> [Category("Behaviour")] [Localizable(true)] public CalendarDisplay CalendarPosition { get { if (ViewState[ViewStateConstants.CalendarPosition.ToString()] == null) { ViewState[ViewStateConstants.CalendarPosition.ToString()] = CalendarDisplay.DisplayRight; } return (CalendarDisplay)ViewState[ViewStateConstants.CalendarPosition.ToString()]; } set { ViewState[ViewStateConstants.CalendarPosition.ToString()] = value; } } /// <summary> /// Text version of the control's value, for use by ASP.NET validators. /// </summary> public string TextValue { get { return txtDate.Text; } } /// <summary> /// Holds the current date value of this control. /// </summary> [Category("Behaviour")] [Localizable(true)] [Bindable(true, BindingDirection.TwoWay)] public DateTime DateValue { get { try { if (txtDate.Text == "") return DateTime.MinValue; DateTime val = DateTime.Parse(txtDate.Text); return val; } catch (ArgumentNullException) { return DateTime.MinValue; } catch (FormatException) { return DateTime.MinValue; } } set { if (value == DateTime.MinValue) { txtDate.Text = ""; } else { txtDate.Text = value.ToShortDateString(); } } } [Category("Behavior"), Themeable(false), DefaultValue("")] public virtual string ValidationGroup { get { if (ViewState[ViewStateConstants.ValidationGroup.ToString()] == null) { return string.Empty; } else { return (string)ViewState[ViewStateConstants.ValidationGroup.ToString()]; } } set { ViewState[ViewStateConstants.ValidationGroup.ToString()] = value; } } /// <summary> /// The label of the exand button. Shown when the calendar is hidden. /// </summary> [Bindable(true)] [Category("Appearance")] [DefaultValue("PickDate")] [Localizable(true)] public string ExpandButtonLabel { get { String s = (String)ViewState[ViewStateConstants.ExpandLabel.ToString()]; return ((s == null) ? "PickDate" : s); } set { ViewState[ViewStateConstants.ExpandLabel.ToString()] = value; } } /// <summary> /// The label of the collapse button. Shown when the calendar is visible. /// </summary> [Bindable(true)] [Category("Appearance")] [DefaultValue("Disabled")] [Localizable(true)] public string CollapseButtonLabel { get { String s = (String)ViewState[ViewStateConstants.CollapseLabel.ToString()]; return ((s == null) ? "Disabled" : s); } set { ViewState[ViewStateConstants.CollapseLabel.ToString()] = value; } } /// <summary> /// Whether to apply the default style. Disable this if you want to apply a custom style, or to use themes and skins /// to style the control. /// </summary> [Category("Appearance")] [DefaultValue(true)] [Localizable(true)] public bool ApplyDefaultStyle { get { if (ViewState[ViewStateConstants.ApplyDefaultStyle.ToString()] == null) { ViewState[ViewStateConstants.ApplyDefaultStyle.ToString()] = true; } return (bool)ViewState[ViewStateConstants.ApplyDefaultStyle.ToString()]; } set { ViewState[ViewStateConstants.ApplyDefaultStyle.ToString()] = value; } } /// <summary> /// Causes Validation /// </summary> [Category("Appearance")] [DefaultValue(false)] [Localizable(false)] public bool CausesValidation { get { if (ViewState[ViewStateConstants.CausesValidation.ToString()] == null) { ViewState[ViewStateConstants.CausesValidation.ToString()] = false; } return (bool)ViewState[ViewStateConstants.CausesValidation.ToString()]; } set { ViewState[ViewStateConstants.CausesValidation.ToString()] = value; btnDate.CausesValidation = value; } } #endregion #region Events /// <summary> /// A day was selected from the calendar control. /// </summary> public event EventHandler SelectionChanged; protected virtual void OnSelectionChanged() { if (SelectionChanged != null) // only raise the event if someone is listening. { SelectionChanged(this, EventArgs.Empty); } } #endregion #region Event Handlers /// <summary> /// The +/- button was clicked. /// </summary> protected void btnDate_Click(object sender, System.EventArgs e) { if (!calDate.Visible) { // expand the calendar calDate.Visible = true; txtDate.Enabled = false; btnDate.Text = CollapseButtonLabel; if (DateValue != DateTime.MinValue) { calDate.SelectedDate = DateValue; calDate.VisibleDate = DateValue; } } else { // collapse the calendar calDate.Visible = false; txtDate.Enabled = true; btnDate.Text = ExpandButtonLabel; } } /// <summary> /// A date was selected from the calendar. /// </summary> protected void calDate_SelectionChanged(object sender, System.EventArgs e) { calDate.Visible = false; txtDate.Visible = true; btnDate.Text = ExpandButtonLabel; txtDate.Enabled = true; txtDate.Text = calDate.SelectedDate.ToShortDateString(); OnSelectionChanged(); } #endregion /// <summary> /// Builds the contents of this control. /// </summary> protected override void CreateChildControls() { btnDate.Text = ExpandButtonLabel; btnDate.CausesValidation = CausesValidation; txtDate.ID = "txtDate"; calDate.Visible = false; if (ApplyDefaultStyle) { calDate.BackColor = System.Drawing.Color.White; calDate.BorderColor = System.Drawing.Color.FromArgb(10066329); calDate.CellPadding = 2; calDate.DayNameFormat = DayNameFormat.Shortest; calDate.Font.Name = "Verdana"; calDate.Font.Size = FontUnit.Parse("8pt"); calDate.ForeColor = System.Drawing.Color.Black; calDate.Height = new Unit(150, UnitType.Pixel); calDate.Width = new Unit(180, UnitType.Pixel); calDate.DayHeaderStyle.BackColor = System.Drawing.Color.FromArgb(228, 228, 228); calDate.DayHeaderStyle.Font.Size = FontUnit.Parse("7pt"); calDate.TitleStyle.Font.Bold = true; calDate.WeekendDayStyle.BackColor = System.Drawing.Color.FromArgb(255, 255, 204); } ConnectEventHandlers(); pnlCalendar.Controls.Add(calDate); pnlCalendar.Style["position"] = "absolute"; pnlCalendar.Style["filter"] = "alpha(opacity=95)"; pnlCalendar.Style["-moz-opacity"] = ".95"; pnlCalendar.Style["opacity"] = ".95"; pnlCalendar.Style["z-index"] = "2"; pnlCalendar.Style["background-color"] = "White"; if (CalendarPosition == CalendarDisplay.DisplayBelow) { pnlCalendar.Style["margin-top"] = "27px"; } else { pnlCalendar.Style["display"] = "inline"; } Controls.Add(txtDate); Controls.Add(pnlCalendar); Controls.Add(btnDate); base.CreateChildControls(); } /// <summary> /// Render the contents of this control. /// </summary> /// <param name="output">The HtmlTextWriter to use.</param> protected override void RenderContents(HtmlTextWriter output) { switch (CalendarPosition) { case CalendarDisplay.DisplayRight: { txtDate.RenderControl(output); btnDate.RenderControl(output); pnlCalendar.RenderControl(output); break; } case CalendarDisplay.DisplayBelow: { pnlCalendar.RenderControl(output); txtDate.RenderControl(output); btnDate.RenderControl(output); break; } } } /// <summary> /// Connect event handlers to events. /// </summary> private void ConnectEventHandlers() { btnDate.Click += new System.EventHandler(btnDate_Click); calDate.SelectionChanged += new System.EventHandler(calDate_SelectionChanged); } } } using System; using System.Collections.Generic; using System.ComponentModel; using System.Text; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; [assembly: TagPrefix("DatePicker", "EWS")] namespace EclipseWebSolutions.DatePicker { [DefaultProperty("Text")] [ToolboxData("<{0}:DatePicker runat=server")] [DefaultEvent("SelectionChanged")] [ValidationProperty("TextValue")] public class DatePicker : WebControl, INamingContainer { #region Properties public TextBox txtDate = new TextBox(); public Calendar calDate = new Calendar(); public Button btnDate = new Button(); public Panel pnlCalendar = new Panel(); private enum ViewStateConstants { ValidationGroup, RegularExpression, ErrorMessage, RegExText, CalendarPosition, FormatString, ExpandLabel, CollapseLabel, ApplyDefaultStyle, CausesValidation, } /// <summary> /// Defines the available display modes of this calendar. /// </summary> public enum CalendarDisplay { DisplayRight, DisplayBelow } /// <summary> /// Where to display the popup calendar. /// </summary> [Category("Behaviour")] [Localizable(true)] public CalendarDisplay CalendarPosition { get { if (ViewState[ViewStateConstants.CalendarPosition.ToString()] == null) { ViewState[ViewStateConstants.CalendarPosition.ToString()] = CalendarDisplay.DisplayRight; } return (CalendarDisplay)ViewState[ViewStateConstants.CalendarPosition.ToString()]; } set { ViewState[ViewStateConstants.CalendarPosition.ToString()] = value; } } /// <summary> /// Text version of the control's value, for use by ASP.NET validators. /// </summary> public string TextValue { get { return txtDate.Text; } } /// <summary> /// Holds the current date value of this control. /// </summary> [Category("Behaviour")] [Localizable(true)] [Bindable(true, BindingDirection.TwoWay)] public DateTime DateValue { get { try { if (txtDate.Text == "") return DateTime.MinValue; DateTime val = DateTime.Parse(txtDate.Text); return val; } catch (ArgumentNullException) { return DateTime.MinValue; } catch (FormatException) { return DateTime.MinValue; } } set { if (value == DateTime.MinValue) { txtDate.Text = ""; } else { txtDate.Text = value.ToShortDateString(); } } } [Category("Behavior"), Themeable(false), DefaultValue("")] public virtual string ValidationGroup { get { if (ViewState[ViewStateConstants.ValidationGroup.ToString()] == null) { return string.Empty; } else { return (string)ViewState[ViewStateConstants.ValidationGroup.ToString()]; } } set { ViewState[ViewStateConstants.ValidationGroup.ToString()] = value; } } /// <summary> /// The label of the exand button. Shown when the calendar is hidden. /// </summary> [Bindable(true)] [Category("Appearance")] [DefaultValue("PickDate")] [Localizable(true)] public string ExpandButtonLabel { get { String s = (String)ViewState[ViewStateConstants.ExpandLabel.ToString()]; return ((s == null) ? "PickDate" : s); } set { ViewState[ViewStateConstants.ExpandLabel.ToString()] = value; } } /// <summary> /// The label of the collapse button. Shown when the calendar is visible. /// </summary> [Bindable(true)] [Category("Appearance")] [DefaultValue("Disabled")] [Localizable(true)] public string CollapseButtonLabel { get { String s = (String)ViewState[ViewStateConstants.CollapseLabel.ToString()]; return ((s == null) ? "Disabled" : s); } set { ViewState[ViewStateConstants.CollapseLabel.ToString()] = value; } } /// <summary> /// Whether to apply the default style. Disable this if you want to apply a custom style, or to use themes and skins /// to style the control. /// </summary> [Category("Appearance")] [DefaultValue(true)] [Localizable(true)] public bool ApplyDefaultStyle { get { if (ViewState[ViewStateConstants.ApplyDefaultStyle.ToString()] == null) { ViewState[ViewStateConstants.ApplyDefaultStyle.ToString()] = true; } return (bool)ViewState[ViewStateConstants.ApplyDefaultStyle.ToString()]; } set { ViewState[ViewStateConstants.ApplyDefaultStyle.ToString()] = value; } } /// <summary> /// Causes Validation /// </summary> [Category("Appearance")] [DefaultValue(false)] [Localizable(false)] public bool CausesValidation { get { if (ViewState[ViewStateConstants.CausesValidation.ToString()] == null) { ViewState[ViewStateConstants.CausesValidation.ToString()] = false; } return (bool)ViewState[ViewStateConstants.CausesValidation.ToString()]; } set { ViewState[ViewStateConstants.CausesValidation.ToString()] = value; btnDate.CausesValidation = value; } } #endregion #region Events /// <summary> /// A day was selected from the calendar control. /// </summary> public event EventHandler SelectionChanged; protected virtual void OnSelectionChanged() { if (SelectionChanged != null) // only raise the event if someone is listening. { SelectionChanged(this, EventArgs.Empty); } } #endregion #region Event Handlers /// <summary> /// The +/- button was clicked. /// </summary> protected void btnDate_Click(object sender, System.EventArgs e) { if (!calDate.Visible) { // expand the calendar calDate.Visible = true; txtDate.Enabled = false; btnDate.Text = CollapseButtonLabel; if (DateValue != DateTime.MinValue) { calDate.SelectedDate = DateValue; calDate.VisibleDate = DateValue; } } else { // collapse the calendar calDate.Visible = false; txtDate.Enabled = true; btnDate.Text = ExpandButtonLabel; } } /// <summary> /// A date was selected from the calendar. /// </summary> protected void calDate_SelectionChanged(object sender, System.EventArgs e) { calDate.Visible = false; txtDate.Visible = true; btnDate.Text = ExpandButtonLabel; txtDate.Enabled = true; txtDate.Text = calDate.SelectedDate.ToShortDateString(); OnSelectionChanged(); } #endregion /// <summary> /// Builds the contents of this control. /// </summary> protected override void CreateChildControls() { btnDate.Text = ExpandButtonLabel; btnDate.CausesValidation = CausesValidation; txtDate.ID = "txtDate"; calDate.Visible = false; if (ApplyDefaultStyle) { calDate.BackColor = System.Drawing.Color.White; calDate.BorderColor = System.Drawing.Color.FromArgb(10066329); calDate.CellPadding = 2; calDate.DayNameFormat = DayNameFormat.Shortest; calDate.Font.Name = "Verdana"; calDate.Font.Size = FontUnit.Parse("8pt"); calDate.ForeColor = System.Drawing.Color.Black; calDate.Height = new Unit(150, UnitType.Pixel); calDate.Width = new Unit(180, UnitType.Pixel); calDate.DayHeaderStyle.BackColor = System.Drawing.Color.FromArgb(228, 228, 228); calDate.DayHeaderStyle.Font.Size = FontUnit.Parse("7pt"); calDate.TitleStyle.Font.Bold = true; calDate.WeekendDayStyle.BackColor = System.Drawing.Color.FromArgb(255, 255, 204); } ConnectEventHandlers(); pnlCalendar.Controls.Add(calDate); pnlCalendar.Style["position"] = "absolute"; pnlCalendar.Style["filter"] = "alpha(opacity=95)"; pnlCalendar.Style["-moz-opacity"] = ".95"; pnlCalendar.Style["opacity"] = ".95"; pnlCalendar.Style["z-index"] = "2"; pnlCalendar.Style["background-color"] = "White"; if (CalendarPosition == CalendarDisplay.DisplayBelow) { pnlCalendar.Style["margin-top"] = "27px"; } else { pnlCalendar.Style["display"] = "inline"; } Controls.Add(txtDate); Controls.Add(pnlCalendar); Controls.Add(btnDate); base.CreateChildControls(); } /// <summary> /// Render the contents of this control. /// </summary> /// <param name="output">The HtmlTextWriter to use.</param> protected override void RenderContents(HtmlTextWriter output) { switch (CalendarPosition) { case CalendarDisplay.DisplayRight: { txtDate.RenderControl(output); btnDate.RenderControl(output); pnlCalendar.RenderControl(output); break; } case CalendarDisplay.DisplayBelow: { pnlCalendar.RenderControl(output); txtDate.RenderControl(output); btnDate.RenderControl(output); break; } } } /// <summary> /// Connect event handlers to events. /// </summary> private void ConnectEventHandlers() { btnDate.Click += new System.EventHandler(btnDate_Click); calDate.SelectionChanged += new System.EventHandler(calDate_SelectionChanged); } } } <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" % <%@ Register Assembly="EclipseWebSolutions.DatePicker" Namespace="EclipseWebSolutions.DatePicker" TagPrefix="ews" % Untitled Page       using System; using System.Data; using System.Configuration; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void DatePicker1_SelectionChanged(object sender, EventArgs e) { Label1.Text = DatePicker1.DateValue.ToShortDateString(); pnlLabel.Update(); } }

    Read the article

  • bootstrap: Uncaught TypeError: Object [object Object] has no method 'tooltip', 'typeahead'

    - by DarkKnightFan
    I am trying to use the tooltip, typeahead, datepicker features of bootstrap. But I keep getting these errors in the console! Uncaught TypeError: Object [object Object] has no method 'tooltip' Uncaught TypeError: Object [object Object] has no method 'typeahead' This is how my imports look like: <link href="css/bootstrap.css" rel="stylesheet"> <link href="css/datepicker.css" rel="stylesheet"> <link href="css/bootstrap-responsive.css" rel="stylesheet"> <script type="text/javascript" src="js/jquery-1.8.0.js"></script> <script type="text/javascript" src="js/bootstrap.js"></script> <script type="text/javascript" src="js/bootstrap-datepicker.js"></script> <script type="text/javascript" src="js/bootstrap-typeahead.js"></script> <script type="text/javascript" src="js/highcharts.js"></script> <script type="text/javascript" src="js/exporting.js"></script> <link type="text/css" rel="stylesheet" href="css/jquery.dropdown.css" /> <script type="text/javascript" src="js/jquery.dropdown.js"></script> Some sample code: <a class="btn btn-success" data-toggle="modal" href="#payments" rel="tooltip" data-placement="top" title="Record your payments"> <i class="icon-check icon-white"></i> Payments</a> $("#payments").tooltip('show'); Similarly I have code for datepicker and typeahead. any solution?

    Read the article

  • Passing an NSDate

    - by Garry
    I'm new to the iPhone and objective-c and I am still trying to get my head around ownership of objects so bear with me. I have a DOBViewController that has a datepicker on it. I have created a custom init method: -(id)initWithInitialDate(NSDate *)initialDate; Another view controller has a date instance declared (NSDate *dob) that holds a value. I would like to pass this to the DOBViewController so that it can scroll the datepicker to the passed value. Here is the custom init method: - (id)initWithInitialDate:(NSDate *)initialDate { // Initialise ourselves self = [super init]; // Set the date of the date picker if (initialDate != nil) { datePicker.date = initialDate; } else { // Set it to today datePicker.date = [NSDate date]; } return self; } This is how I am sending the dob NSDate object: DOBViewController *dobViewController = [[DOBViewController alloc] initWithInitialDate:dob]; Where dob is a variable of type NSDate that is declared in the header file. This doesn't seem to work as initialDate is always NULL. What am I doing wrong?

    Read the article

  • how to incorporate a function within a function

    - by bklynM
    I updated my code with string dates created with new Date and added back in the if statement. This isn't disabling the string or range though. I've added the datepicker code too. function unavailableDays(date) { function createDateRange(first, last) { var dates = []; for(var j = first; j < last; j.setDate(j.getDate() + 7)) { dates.push(new Date(j.getTime())); } var alwaysDisabled = [new Date("1963-3-10T00:00:00"), new Date("1963-3-17T00:00:00"), new Date("1963-3-24T00:00:00"), new Date("1963-3-31T00:00:00"), new Date("1965-9-18T00:00:00")]; return dates.concat(alwaysDisabled); } var disabledDays = createDateRange(new Date("1978-8-10T00:00:00"), new Date("1978-11-5T00:00:00")); var yy = date.getFullYear(), mm = date.getMonth(), dd = date.getDate(); for (i = 0; i < disabledDays.length; i++) { if($.inArray(yy + '-' + (mm+1) + '-' + dd,disabledDays) != -1 || new Date() < date) { return [false]; } } return [true]; } $(document).ready(function (){ $('.selector').datepicker({ inline: true, dateFormat: 'yy-mm-dd', constrainInput: true, changeYear: true, changeMonth: true, minDate: new Date(1940, 1-1, 1), maxDate: new Date(2011, 10-1, 24), beforeShowDay: unavailableDays, onSelect: function(dateText, inst) { $("#img").attr("src", "http://www.example.com" + dateText + ".jpg"); var chosenDates = $.datepicker.parseDate('yy-mm-dd', dateText); var backToString = $.datepicker.formatDate('MM dd' + ',' + ' yy', chosenDates); $('.info').html('You are viewing:' + '<br />' + backToString).addClass('background'); } }); });

    Read the article

  • jquery validator message styling error in IE08 only when customised using errorPlacement function

    - by John Slaytor
    Going back to the errorplacement solution by Nadia (http://stackoverflow.com/questions/860055/jquery-override-default-validation-error-message-display-css-popup-tooltip-like) I have tried it and it works like a charm in Safari and Firefox but causes IE08 to bypass the jqueryvalidator and go straight to the server side validator. My code is this - as soon as I insert 'error element.... it is unstable in IE08. All help much appreciated <script type="text/javascript"> $(document).ready(function() { $("#sampleform").validate({ rules: { dinername: "required", venue: "required", contact: "required", dinertelephone: "required", venuetime: "required", numberdiners: "required", dineremail: { required: true, email: true}, datepicker: { required: true,date: true} }, messages: { dinername: "Your name?", numberdiners: "How many guests?", dinertelephone: "Your mobile?", venue: "Which restaurant?", venuetime: "Your arrival time?", datepicker: "Your booking date?", dineremail: "Please enter a valid email address", }, errorElement: "div", errorPlacement: function(error, element) { element.before(error); offset = element.offset(); error.css('right', offset.right); error.css('right', offset.right - element.outerHeight()); } }); }); </script> <script type="text/javascript"> $(function() { $("#datepicker") .datepicker({minDate: 0, maxDate: '+6M +0D',dateFormat: 'DD, d M yy',onClose: function() {$(this).valid();} }); }); </script> The relevant webpage is http://www.johnslaytor.com.au/nilgiris/forms/bookingform/bookingform.html

    Read the article

  • How to apply CSS theme to only a specific jQuery-UI element?

    - by Thierry-Dimitri Roy
    I have a web site already build with my own CSS theme. I'm using jQuery UI "tabs" widget but no CSS from jQuery-UI. Now, I'm trying to add the "Date Picker" widget in one of my page. It would be great if I could reuse jQuery-UI default theme which is just fine. The problem is that the date picker theme is also applied to my tabs CSS. For example the "ui-widget" css properties is applied to both date picker and tabs elements. I can't seem to find a way to apply the css properties to only the date picker. I can't see a "super selector" that only applies to the date picker DIV. What would be the best way to handle this? [EDIT] The datepicker widget is really the problem. I cannot apply CSS style specific to it. Here is the starting code of the DIV that get pops up: <div style="position: absolute; top: 300.4px; left: 149px; display: block;" id="ui-datepicker-div" class="ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all ui-helper-hidden-accessible"><div class="ui-datepicker-header ui-widget-header ui-helper-clearfix ui-corner-all"> As such, I cannot add a super selector. What would be great would be that the date picker widget supports CSS scope. But it does not. I'm stuck manually editing the jQuery CSS file. The Date Picker is currently being refactored. Hopefully the new code will address this issue.

    Read the article

  • JQuery date picker does not firing in ajax page using Rails

    - by prabu
    Hi Here I have using datepicker from JQueryUI in my public/javascript folder as effects,prototype,control,dragdrop js files. in my public folder contains jqueryui development buddle. (css,js,development-bundle) in layout/application.rhtml <%= stylesheet_link_tag 'application' %> <%=javascript_include_tag :defaults%> <%= stylesheet_link_tag '/jquery-ui/css/custom-theme/jquery-ui-1.8.1.custom.css' %> <%=javascript_include_tag "/jquery-ui/js/jquery-1.4.2.min.js"%> <%=javascript_include_tag "/jquery-ui/js/jquery-ui-1.8.1.custom.min.js"%> <script> $(document).ready(function(){ var $j=jQuery.noConflict(); $j( '#date' ).datepicker({ dateFormat: 'dd-mm-yy' }); }); </script> in home/index.rhtml <%title "Home"%> <%=link_to "Add Details" ,:action=>"add"%> <%=link_to_remote "Ajax Add Details", :update=>"add" , :url=>{ :action=>"add" }%> <div id='add' /> in home/add.rhtml <%title "Add details"%> <%form_tag :action=>"create" do%> Name : <%=text_field_tag "name" ,"",:size=>15%> DOB : <%=text_field_tag "dob","",:id=>"date"%> <%=submit_tag "Save"%> <%end%> the datepicker works when I run home/add.rhtml directly but the datepicker not work when i run ajax page home/index.rhtml Any solutions for that,????

    Read the article

  • ZendX Jquery Decorator

    - by iJD
    How use partial decorator in Jquery Element I use this code for Form Element: $title = new Zend_Form_Element_Text('title'); $title->setRequired(true) ->setAttrib('class', 'inputbox') ->setLabel('Title'); $title->viewScript = 'RegElement.phtml'; $title->setDecorators( array( array('ViewScript', array('class' => 'RegElement')) ) ); But when i use Jquery Element i dont know how implement it: $datePicker = new ZendX_JQuery_Form_Element_DatePicker( "datePicker1", array("label" => "Date:") ); $datePicker->viewScript = 'RegElement.phtml'; $datePicker->setDecorators( array( array('ViewScript', array('class' => 'RegElement')) ) ); //views/scripts/RegElement.phtml <li class="row <?php echo $this->class ?>"> <div class="cont-error"> <?php echo $this->formErrors($this->element->getMessages()); ?> </div> <div class="rowfields"> <?php echo $this->formLabel($this->element->getName(), $this->element->getLabel()) ?> <?php echo $this->{$this->element->helper}( $this->element->getName(), $this->element->getValue(), $this->element->getAttribs() ) ?> </div> <div class="hint"><?php echo $this->element->getDescription() ?></div> </li> And display this error: Warning: Exception caught by form: Cannot render jQuery form element without at least one decorator implementing the 'ZendX_JQuery_Form_Decorator_UiWidgetElementMarker' interface. I need display datePicker with same format. but idk how implement this interface. thx for your help.

    Read the article

  • How can I combine a LINQ query with an IQueryable<Guid>

    - by John
    I have a LINQ query that uses 1 table + a large number of views. I'd like to be able to write something like this: IQueryable<Guid> mostViewedWriters; switch (datePicker) { case DatePicker.Last12Hours: mostViewedWriters = from x in context.tempMostViewed12Hours select x.GuidId; break; case DatePicker.Last24Hours: mostViewedWriters = from x in context.tempMostViewed12Hours select x.GuidId; break; case DatePicker.Last36Hours: mostViewedWriters = from x in context.tempMostViewed12Hours select x.GuidId; break; } var query = from x1 in context.Articles join x2 in context.Authors on x1.AuthorId == x2.AuthorId join x3 in mostViewedWriters on x2.AuthorId == x3.Id select new { x2.AuthorName, x1.ArticleId, x1.ArticleTitle }; The above C# is pseudo-code written to protect the innocent (me). The gist of the question is this: I have a query that is related to the results of a view. That view, however, could be one of many different views. All the views return the same data type. I thought that I might be able to create an IQueryable that would contain the Ids that I need and use that query. Alas, that effort has stalled.

    Read the article

  • where is this function getting its values from

    - by user295189
    I have the JS file below that I am working on and I have a need to know this specific function pg.getRecord_Response = function(){ } within the file. I need to know where are the values are coming from in this function for example arguments[0].responseText? I am new to javascript so any help will be much appreciated. Thanks var pg = new Object(); var da = document.body.all; // ===== - EXPRESS BUILD [REQUEST] - ===== // pg.expressBuild_Request = function(){ var n = new Object(); n.patientID = request.patientID; n.encounterID = request.encounterID; n.flowSheetID = request.flowSheetID; n.encounterPlan = request.encounterPlan; n.action = "/location/diagnosis/dsp_expressBuild.php"; n.target = popWinCenterScreen("/common/html/empty.htm", 619, 757, ""); myLocationDB.PostRequest(n); } // ===== - EXPRESS BUILD [RESPONSE] - ===== // pg.expressBuild_Response = function(){ pg.records.showHiddenRecords = 0; pg.loadRecords_Request(arguments.length ? arguments[0] : 0); } // ===== - GET RECORD [REQUEST] - ===== // pg.getRecord_Request = function(){ if(pg.records.lastSelected){ pg.workin(true); pg.record.recordID = pg.records.lastSelected.i; var n = new Object(); n.noheaders = 1; n.recordID = pg.record.recordID; myLocationDB.Ajax.Post("/location/diagnosis/get_record.php", n, pg.getRecord_Response); } else { pg.buttons.btnOpen.disable(true); } } // ===== - GET RECORD [RESPONSE] - ===== // pg.getRecord_Response = function(){ //alert(arguments[0].responseText); if(arguments.length && arguments[0].responseText){ alert(arguments[0].responseText); // Refresh PQRI grid when encounter context if(request.encounterID && window.parent.frames['main']){ window.parent.frames['main'].pg.loadQualityMeasureRequest(); } var rec = arguments[0].responseText.split(pg.delim + pg.delim); if(rec.length == 20){ // validate record values rec[0] = parseInt(rec[0]); rec[3] = parseInt(rec[3]); rec[5] = parseInt(rec[5]); rec[6] = parseInt(rec[6]); rec[7] = parseInt(rec[7]); rec[8] = parseInt(rec[8]); rec[9] = parseInt(rec[9]); rec[10] = parseInt(rec[10]); rec[11] = parseInt(rec[11]); rec[12] = parseInt(rec[12]); rec[15] = parseInt(rec[15]); // set record state pg.recordState = { recordID: pg.record.recordID, codeID: rec[0], description: rec[2], assessmentTypeID: rec[3], type: rec[4], onsetDateYear: rec[5], onsetDateMonth: rec[6], onsetDateDay: rec[7], onsetDateIsApproximate: rec[8], resolveDateYear: rec[9], resolveDateMonth: rec[10], resolveDateDay: rec[11], resolveDateIsApproximate: rec[12], commentsCount: rec[15], comments: rec[16] } // set record view pg.record.code.codeID = pg.recordState.codeID; pg.record.code.value = rec[1]; pg.record.description.value = rec[2]; for(var i=0; i<pg.record.type.options.length; i++){ if(pg.record.type.options[i].value == rec[4]){ pg.record.type.selectedIndex = i; break; } } for(var i=0; i<pg.record.assessmentType.options.length; i++){ if(pg.record.assessmentType.options[i].value == rec[3]){ pg.record.assessmentType.selectedIndex = i; break; } } if(rec[5]){ if(rec[6] && rec[7]){ pg.record.onsetDateType.selectedIndex = 0; pg.record.onsetDate.value = rec[6] + "/" + rec[7] + "/" + rec[5]; pg.record.onsetDate.format(); } else { pg.record.onsetDateType.selectedIndex = 1; pg.record.onsetDateMonth.selectedIndex = rec[6]; for(var i=0; i<pg.record.onsetDateYear.options.length; i++){ if(pg.record.onsetDateYear.options[i].value == rec[5]){ pg.record.onsetDateYear.selectedIndex = i; break; } } if(rec[8]) pg.record.chkOnsetDateIsApproximate.checked = true; } } else { pg.record.onsetDateType.selectedIndex = 2; } if(rec[9]){ if(rec[10] && rec[11]){ pg.record.resolveDateType.selectedIndex = 0; pg.record.resolveDate.value = rec[10] + "/" + rec[11] + "/" + rec[9]; pg.record.resolveDate.format(); } else { pg.record.resolveDateType.selectedIndex = 1; pg.record.resolveDateMonth.selectedIndex = rec[10]; for(var i=0; i<pg.record.resolveDateYear.options[i].length; i++){ if(pg.record.resolveDateYear.options.value == rec[9]){ pg.record.resolveDateYear.selectedIndex = i; break; } } if(rec[12]) pg.record.chkResolveDateIsApproximate.checked = true; } } else { pg.record.resolveDateType.selectedIndex = 2; } pg.record.lblCommentCount.innerHTML = rec[15]; pg.record.comments.value = rec[16]; pg.record.lblUpdatedBy.innerHTML = "* Last updated by " + rec[13] + " on " + rec[14]; pg.record.lblUpdatedBy.title = "Updated by: " + rec[13] + "\nUpdated on: " + rec[14]; pg.record.linkedNotes.setData(rec[18]); pg.record.linkedOrders.setData(rec[19]); pg.record.updates.setData(rec[17]); return; } } alert("An error occured while attempting to retrieve\ndetails for record #" + pg.record.recordID + ".\n\nPlease contact support if this problem persists.\nWe apologize for the inconvenience."); pg.hideRecordView(); } // ===== - HIDE COMMENTS VIEW - ===== // pg.hideCommentsView = function(){ pg.recordComments.style.left = ""; pg.recordComments.disabled = true; pg.recordComments.comments.value = ""; pg.record.disabled = false; pg.record.style.zIndex = 5500; } // ===== - HIDE code SEARCH - ===== // pg.hidecodeSearch = function(){ pg.codeSearch.style.left = ""; pg.codeSearch.disabled = true; pg.record.disabled = false; pg.record.style.zIndex = 5500; } // ===== - HIDE RECORD - ===== // pg.hideRecord = function(){ if(arguments.length){ pg.loadRecords_Request(); } else if(pg.records.lastSelected){ var n = new Object(); n.recordTypeID = 11; n.patientID = request.patientID; n.recordID = pg.records.lastSelected.i; n.action = "/location/hideRecord/dsp_hideRecord.php"; n.target = popWinCenterScreen("/common/html/empty.htm", 164, 476); myLocationDB.PostRequest(n); } } // ===== - HIDE RECORD VIEW - ===== // pg.hideRecordView = function(){ pg.record.style.left = ""; pg.record.disabled = true; // reset record grids pg.record.updates.state = "NO_RECORDS"; pg.record.linkedNotes.state = "NO_RECORDS"; pg.record.linkedOrders.state = "NO_RECORDS"; // reset linked record tabs pg.record.tabs[0].click(); pg.record.tabs[1].disable(true); pg.record.tabs[2].disable(true); pg.record.tabs[1].all[1].innerHTML = "Notes"; pg.record.tabs[2].all[1].innerHTML = "Orders"; // reset record state pg.recordState = null; // reset record view pg.record.recordID = 0; pg.record.code.value = ""; pg.record.code.codeID = 0; pg.record.description.value = ""; pg.record.type.selectedIndex = 0; pg.record.assessmentType.selectedIndex = 0; pg.record.onsetDateType.selectedIndex = 0; pg.record.chkOnsetDateIsApproximate.checked = false; pg.record.resolveDateType.selectedIndex = 0; pg.record.chkResolveDateIsApproximate.checked = false; pg.record.lblCommentCount.innerHTML = 0; pg.record.comments.value = ""; pg.record.lblUpdatedBy.innerHTML = ""; pg.record.lblUpdatedBy.title = ""; pg.record.updateComment = ""; pg.recordComments.comments.value = ""; pg.record.active = false; pg.codeSearch.newRecord = true; pg.blocker.className = ""; pg.workin(false); } // ===== - HIDE UPDATE VIEW - ===== // pg.hideUpdateView = function(){ pg.recordUpdate.style.left = ""; pg.recordUpdate.disabled = true; pg.recordUpdate.type.value = ""; pg.recordUpdate.onsetDate.value = ""; pg.recordUpdate.description.value = ""; pg.recordUpdate.resolveDate.value = ""; pg.recordUpdate.assessmentType.value = ""; pg.record.disabled = false; pg.record.btnViewUpdate.setState(); pg.record.style.zIndex = 5500; } // ===== - INIT - ===== // pg.init = function(){ var tab = 1; pg.delim = String.fromCharCode(127); pg.subDelim = String.fromCharCode(1); pg.blocker = da.blocker; pg.hourglass = da.hourglass; pg.pageContent = da.pageContent; pg.blocker.shim = da.blocker_shim; pg.activeTip = da.activeTip; pg.activeTip.anchor = null; pg.activeTip.shim = da.activeTip_shim; // PAGE TITLE pg.pageTitle = da.pageTitle; // TOTAL RECORDS pg.totalRecords = da.totalRecords[0]; // START RECORD pg.startRecord = da.startRecord[0]; pg.startRecord.onchange = function(){ pg.records.startRecord = this.value; pg.loadRecords_Request(); } // RECORD PANEL pg.recordPanel = myLocationDB.RecordPanel(pg.pageContent.all.recordPanel); for(var i=0; i<pg.recordPanel.buttons.length; i++){ if(pg.recordPanel.buttons[i].orderBy){ pg.recordPanel.buttons[i].onclick = pg.sortRecords; } } // RECORDS GRIDVIEW pg.records = pg.recordPanel.all.grid; alert(pg.recordPanel.all.grid); pg.records.sortOrder = "DESC"; pg.records.lastExpanded = null; pg.records.attachEvent("onrowclick", pg.record_click); pg.records.orderBy = pg.recordPanel.buttons[0].orderBy; pg.records.attachEvent("onrowmouseout", pg.record_mouseOut); pg.records.attachEvent("onrowdblclick", pg.getRecord_Request); pg.records.attachEvent("onrowmouseover", pg.record_mouseOver); pg.records.attachEvent("onstateready", pg.loadRecords_Response); // BUTTON - TOGGLE HIDDEN RECORDS pg.btnHiddenRecords = myLocationDB.Custom.ImageButton(3, 751, 19, 19, "/common/images/hide.gif", 1, 1, "", "", da.pageContent); pg.btnHiddenRecords.setTitle("Show hidden records"); pg.btnHiddenRecords.onclick = pg.toggleHiddenRecords; pg.btnHiddenRecords.setState = function(){ this.disable(!pg.records.totalHiddenRecords); } // code SEARCH SUBWIN pg.codeSearch = da.subWin_codeSearch; pg.codeSearch.newRecord = true; pg.codeSearch.searchType = "code"; pg.codeSearch.searchFavorites = true; pg.codeSearch.onkeydown = function(){ if(window.event && window.event.keyCode && window.event.keyCode == 113){ if(pg.codeSearch.searchType == "DESCRIPTION"){ pg.codeSearch.searchType = "code"; pg.codeSearch.lblSearchType.innerHTML = "ICD-9 Code"; } else { pg.codeSearch.searchType = "DESCRIPTION"; pg.codeSearch.lblSearchType.innerHTML = "Description"; } pg.searchcodes_Request(); } } // SEARCH TYPE pg.codeSearch.lblSearchType = pg.codeSearch.all.lblSearchType; // SEARCH STRING pg.codeSearch.searchString = pg.codeSearch.all.searchString; pg.codeSearch.searchString.tabIndex = 1; pg.codeSearch.searchString.onfocus = function(){ this.select(); } pg.codeSearch.searchString.onblur = function(){ this.value = this.value.trim(); } pg.codeSearch.searchString.onkeydown = function(){ if(window.event && window.event.keyCode && window.event.keyCode == 13){ pg.searchcodes_Request(); } } // -- "SEARCH" pg.codeSearch.btnSearch = pg.codeSearch.all.btnSearch; pg.codeSearch.btnSearch.tabIndex = 2; pg.codeSearch.btnSearch.disable = myLocationDB.Disable; pg.codeSearch.btnSearch.onclick = pg.searchcodes_Request; pg.codeSearch.btnSearch.baseTitle = "Search diagnosis codes"; pg.codeSearch.btnSearch.setState = function(){ pg.codeSearch.btnSearch.disable(pg.codeSearch.searchString.value.trim().length < 2); } pg.codeSearch.searchString.onkeyup = pg.codeSearch.btnSearch.setState; // START RECORD / TOTAL RECORDS pg.codeSearch.startRecord = pg.codeSearch.all.startRecord; pg.codeSearch.totalRecords = pg.codeSearch.all.totalRecords; pg.codeSearch.startRecord.onchange = function(){ pg.codeSearch.records.startRecord = this.value; pg.searchcodes_Request(); } // RECORD PANEL pg.codeSearch.recordPanel = myLocationDB.RecordPanel(pg.codeSearch.all.recordPanel); pg.codeSearch.recordPanel.buttons[0].onclick = pg.sortcodeResults; pg.codeSearch.recordPanel.buttons[1].onclick = pg.sortcodeResults; // DATA GRIDVIEW pg.codeSearch.records = pg.codeSearch.all.grid; pg.codeSearch.records.orderBy = "code"; pg.codeSearch.records.attachEvent("onrowdblclick", pg.updatecode); pg.codeSearch.records.attachEvent("onstateready", pg.searchcodes_Response); // BUTTON - "CANCEL" pg.codeSearch.btnCancel = pg.codeSearch.all.btnCancel; pg.codeSearch.btnCancel.tabIndex = 4; pg.codeSearch.btnCancel.onclick = pg.hidecodeSearch; pg.codeSearch.btnCancel.title = "Close this search area"; // SEARCH FAVORITES / ALL pg.codeSearch.optSearch = myLocationDB.InputButton(pg.codeSearch.all.optSearch); pg.codeSearch.optSearch[0].onclick = function(){ if(pg.codeSearch.searchFavorites){ pg.codeSearch.searchString.focus(); } else { pg.codeSearch.searchFavorites = true; pg.searchcodes_Request(); } } pg.codeSearch.optSearch[1].onclick = function(){ if(pg.codeSearch.searchFavorites){ pg.codeSearch.searchFavorites = false; pg.searchcodes_Request(); } else { pg.codeSearch.searchString.focus(); } } // -- "USE SELECTED" pg.codeSearch.btnUseSelected = pg.codeSearch.all.btnUseSelected; pg.codeSearch.btnUseSelected.tabIndex = 3; pg.codeSearch.btnUseSelected.onclick = pg.updatecode; pg.codeSearch.btnUseSelected.disable = myLocationDB.Disable; pg.codeSearch.btnUseSelected.baseTitle = "Use the selected diagnosis code"; pg.codeSearch.btnUseSelected.setState = function(){ pg.codeSearch.btnUseSelected.disable(!pg.codeSearch.records.lastSelected); } pg.codeSearch.records.attachEvent("onrowclick", pg.codeSearch.btnUseSelected.setState); // RECORD STATE pg.recordState = null; // RECORD SUBWIN pg.record = da.subWin_record; pg.record.recordID = 0; pg.record.active = false; pg.record.updateComment = ""; // -- TABS pg.record.tabs = myLocationDB.TabCollection( pg.record.all.tab, function(){ if(pg.record.tabs[0].all[0].checked){ pg.record.btnOpen.style.display = "none"; pg.record.chkSelectAll.hitArea.style.display = "none"; pg.record.btnSave.style.display = "block"; pg.record.lblUpdatedBy.style.display = "block"; pg.record.pnlRecord_shim.style.display = "none"; } else { pg.record.pnlRecord_shim.style.display = "block"; pg.record.btnSave.style.display = "none"; pg.record.lblUpdatedBy.style.display = "none"; pg.record.btnOpen.setState(); pg.record.btnOpen.style.display = "block"; if(pg.record.tabs[2].all[0].checked){ pg.record.chkSelectAll.hitArea.style.display = "none"; //pg.record.btnViewLabs.setState(); //pg.record.btnViewLabs.style.display = "block"; } else { pg.record.chkSelectAll.setState(); pg.record.chkSelectAll.hitArea.style.display = "block"; //pg.record.btnViewLabs.style.display = "none"; } } } ); pg.record.tabs[1].disable(true); pg.record.tabs[2].disable(true); pg.record.pnlRecord_shim = pg.record.all.pnlRecord_shim; pg.record.code = pg.record.all.code; pg.record.code.codeID = 0; pg.record.code.tabIndex = -1; // -- CHANGE code pg.record.btnChangecode = myLocationDB.Custom.ImageButton(6, 107, 22, 22, "/common/images/edit.gif", 2, 2, "", "", pg.record.all.pnlRecord); pg.record.btnChangecode.tabIndex = 1; pg.record.btnChangecode.onclick = pg.showcodeSearch; pg.record.btnChangecode.title = "Change the diagnosis code for this problem"; pg.record.description = pg.record.all.description; pg.record.description.tabIndex = 2; pg.record.type = pg.record.all.type; pg.record.type.tabIndex = 3; pg.record.assessmentType = pg.record.all.assessmentType; pg.record.assessmentType.tabIndex = 9; // ONSET DATE pg.record.onsetDateType = pg.record.all.onsetDateType; pg.record.onsetDateType.tabIndex = 4; pg.record.onsetDateType.onchange = pg.record.onsetDateType.setState = function(){ switch(this.selectedIndex){ case 1: // PARTIAL pg.record.chkOnsetDateIsApproximate.disable(false); pg.record.onsetDate.style.visibility = "hidden"; pg.record.onsetDateUnknown.style.visibility = "hidden"; pg.record.onsetDate.datePicker.style.visibility = "hidden"; pg.record.onsetDateMonth.style.visibility = "visible"; pg.record.onsetDateYear.style.visibility = "visible"; break; case 2: // UNKNOWN pg.record.chkOnsetDateIsApproximate.disable(true); pg.record.onsetDate.style.visibility = "hidden"; pg.record.onsetDateYear.style.visibility = "hidden"; pg.record.onsetDateMonth.style.visibility = "hidden"; pg.record.onsetDate.datePicker.style.visibility = "hidden"; pg.record.onsetDateUnknown.style.visibility = "visible"; break; default: // "WHOLE" pg.record.chkOnsetDateIsApproximate.disable(true); pg.record.onsetDateMonth.style.visibility = "hidden"; pg.record.onsetDateYear.style.visibility = "hidden"; pg.record.onsetDateUnknown.style.visibility = "hidden"; pg.record.onsetDate.style.visibility = "visible"; pg.record.onsetDate.datePicker.style.visibility = "visible"; break; } } pg.record.onsetDate = myLocationDB.Custom.DateInput(30, 364, 80, pg.record.all.pnlRecord, 1, 1, 0, params.todayDate, 1); pg.record.onsetDate.tabIndex = 5; pg.record.onsetDate.style.textAlign = "LEFT"; pg.record.onsetDate.calendar.style.zIndex = 6000; pg.record.onsetDate.datePicker.style.left = "448px"; pg.record.onsetDate.setDateRange(params.birthDate, params.todayDate); pg.record.onsetDateYear = pg.record.all.onsetDateYear; pg.record.onsetDateYear.tabIndex = 6; pg.record.onsetDateMonth = pg.record.all.onsetDateMonth pg.record.onsetDateMonth.tabIndex = 7; pg.record.onsetDateUnknown = pg.record.all.onsetDateUnknown; pg.record.onsetDateUnknown.tabIndex = 8; pg.record.chkOnsetDateIsApproximate = myLocationDB.InputButton(pg.record.all.chkOnsetDateIsApproximate); pg.record.chkOnsetDateIsApproximate.setTitle("Onset date is approximate"); pg.record.chkOnsetDateIsApproximate.disable(true); // RESOLVE DATE pg.record.lblResolveDate = pg.record.all.lblResolveDate; pg.record.resolveDateType = pg.record.all.resolveDateType; pg.record.resolveDateType.tabIndex = 10; pg.record.resolveDateType.lastSelectedIndex = 0; pg.record.resolveDateType.setState = function(){ switch(this.selectedIndex){ case 1: // PARTIAL pg.record.chkResolveDateIsApproximate.disable(false); pg.record.resolveDate.style.visibility = "hidden"; pg.record.resolveDateUnknown.style.visibility = "hidden"; pg.record.resolveDate.datePicker.style.visibility = "hidden"; pg.record.resolveDateMonth.style.visibility = "visible"; pg.record.resolveDateYear.style.visibility = "visible"; break; case 2: // UNKNOWN pg.record.chkResolveDateIsApproximate.disable(true); pg.record.resolveDate.style.visibility = "hidden"; pg.record.resolveDateYear.style.visibility = "hidden"; pg.record.resolveDateMonth.style.visibility = "hidden"; pg.record.resolveDate.datePicker.style.visibility = "hidden"; pg.record.resolveDateUnknown.style.visibility = "visible"; break; default: // "WHOLE" pg.record.chkResolveDateIsApproximate.disable(true); pg.record.resolveDateMonth.style.visibility = "hidden"; pg.record.resolveDateYear.style.visibility = "hidden"; pg.record.resolveDateUnknown.style.visibility = "hidden"; pg.record.resolveDate.style.visibility = "visible"; pg.record.resolveDate.datePicker.style.visibility = "visible"; break; } } pg.record.resolveDateType.onchange = function(){ this.lastSelectedIndex = this.selectedIndex; this.setState(); } pg.record.resolveDate = myLocationDB.Custom.DateInput(55, 364, 80, pg.record.all.pnlRecord, 1, 1, 0, params.todayDate, 1); pg.record.resolveDate.tabIndex = 11; pg.record.resolveDate.style.textAlign = "LEFT"; pg.record.resolveDate.calendar.style.zIndex = 6000; pg.record.resolveDate.datePicker.style.left = "448px"; pg.record.resolveDate.setDateRange(params.birthDate, params.todayDate); pg.record.resolveDate.setState = function(){ if(pg.record.assessmentType.value == 15){ pg.record.chkResolveDateIsApproximate.disable(pg.record.resolveDateType.value != "PARTIAL"); pg.record.resolveDate.disabled = false; pg.record.lblResolveDate.disabled = false; pg.record.resolveDateType.selectedIndex = pg.record.resolveDateType.lastSelectedIndex; pg.record.resolveDateType.setState(); pg.record.resolveDate.datePicker.disable(false); pg.record.resolveDateType.disabled = false; pg.record.resolveDateYear.disabled = false; pg.record.resolveDateMonth.disabled = false; pg.record.resolveDateUnknown.disabled = false; } else { pg.record.resolveDate.datePicker.disable(true); pg.record.chkResolveDateIsApproximate.disable(true); pg.record.resolveDateType.selectedIndex = 2; pg.record.resolveDateType.setState(); pg.record.resolveDate.disabled = true; pg.record.lblResolveDate.disabled = true; pg.record.resolveDateType.disabled = true; pg.record.resolveDateYear.disabled = true; pg.record.resolveDateMonth.disabled = true; pg.record.resolveDateUnknown.disabled = true; } } pg.record.assessmentType.onchange = pg.record.resolveDate.setState; pg.record.resolveDateYear = pg.record.all.resolveDateYear; pg.record.resolveDateYear.tabIndex = 11; pg.record.resolveDateMonth = pg.record.all.resolveDateMonth pg.record.resolveDateMonth.tabIndex = 12; pg.record.resolveDateUnknown = pg.record.all.resolveDateUnknown; pg.record.resolveDateUnknown.tabIndex = 13; pg.record.chkResolveDateIsApproximate = myLocationDB.InputButton(pg.record.all.chkResolveDateIsApproximate); pg.record.chkResolveDateIsApproximate.setTitle("Resolve date is approximate"); pg.record.chkResolveDateIsApproximate.disable(true); // -- UPDATES pg.record.updates = pg.record.all.pnlUpdates.all.grid; pg.record.lblUpdateCount = pg.record.all.lblUpdateCount; pg.record.updates.attachEvent("onstateready", pg.showRecordView); pg.record.updates.attachEvent("onrowdblclick", pg.showUpdateView); // -- "VIEW SELECTED" pg.record.btnViewUpdate = myLocationDB.PanelButton(pg.record.all.btnViewUpdate); pg.record.btnViewUpdate.setTitle("View details for the selected problem update"); pg.record.btnViewUpdate.onclick = pg.showUpdateView; pg.record.btnViewUpdate.setState = function(){ pg.record.btnViewUpdate.disable(!pg.record.updates.lastSelected); } pg.record.updates.attachEvent("onrowclick", pg.record.btnViewUpdate.setState); // -- COMMENTS pg.record.comments = pg.record.all.comments; pg.record.pnlComments = pg.record.all.pnlComments; pg.record.lblCommentCount = pg.record.all.lblCommentCount; // -- UPDATE COMMENTS pg.record.btnUpdateComments = myLocationDB.PanelButton(pg.record.all.btnUpdateComments); pg.record.btnUpdateComments.onclick = pg.showCommentView; pg.record.btnUpdateComments.title = "Update this record's comments"; // -- LINKED NOTES pg.record.linkedNotes = pg.record.all.linkedNotes.all.grid; pg.record.linkedNotes.attachEvent("onrowclick", pg.linkedRecordClick); pg.record.linkedNotes.attachEvent("onrowdblclick", pg.openLinkedNote); pg.record.linkedNotes.attachEvent("onstateready", pg.setLinkedNotes_Count); // -- LINKED ORDERS pg.record.linkedOrders = pg.record.all.linkedOrders.all.grid; pg.record.linkedOrders.attachEvent("onrowclick", pg.linkedRecordClick); pg.record.linkedOrders.attachEvent("onrowdblclick", pg.openLinkedOrder); pg.record.linkedOrders.attachEvent("onstateready", pg.setLinkedOrders_Count); // -- "CLOSE" pg.record.btnClose = pg.record.all.btnClose; pg.record.btnClose.tabIndex = 15; pg.record.btnClose.onclick = pg.hideRecordView; pg.record.btnClose.title = "Close this record panel"; // -- LAST UPDATED BY pg.record.lblUpdatedBy = pg.record.all.lblUpdatedBy; // -- "SELECT ALL" pg.record.chkSelectAll = myLocationDB.InputButton(pg.record.all.chkSelectAll); pg.record.chkSelectAll.onclick = function(){ if(pg.record.tabs[1].all[0].checked){ if(pg.record.chkSelectAll.checked){ pg.record.linkedNotes.selectAll(); } else { pg.record.linkedNotes.deselectAll(); } } else { if(pg.record.chkSelectAll.checked){ pg.record.linkedOrders.selectAll(); } else { pg.record.linkedOrders.deselectAll(); } } pg.record.btnOpen.setState(); //pg.record.btnViewLabs.setState(); } pg.record.chkSelectAll.setState = function(){ if(pg.record.tabs[1].all[0].checked){ pg.record.chkSelectAll.checked = pg.record.linkedNotes.selectedRows.length == pg.record.linkedNotes.rows.length; } else { pg.record.chkSelectAll.checked = pg.record.linkedOrders.selectedRows.length == pg.record.linkedOrders.rows.length; } } // -- "OPEN SELECTED" pg.record.btnOpen = pg.record.all.btnOpenSelected; pg.record.btnOpen.tabIndex = 14; pg.record.btnOpen.disable = myLocationDB.Disable; pg.record.btnOpen.title = "Open the selected record"; pg.record.btnOpen.onclick = function(){ if(pg.record.tabs[1].all[0].checked){ pg.openLinkedNote(); } else if(pg.record.tabs[2].all[0].checked){ pg.openLinkedOrder(); } else { pg.record.btnOpen.disable(true); } } pg.record.btnOpen.setState = function(){ if(pg.record.tabs[1].all[0].checked){ pg.record.btnOpen.disable(!pg.record.linkedNotes.lastSelected); } else if(pg.record.tabs[2].all[0].checked){ pg.record.btnOpen.disable(pg.record.linkedOrders.selectedRows.length != 1); } else { pg.record.btnOpen.disable(true); } } // -- "SAVE" pg.record.btnSave = pg.record.all.btnSave; pg.record.btnSave.tabIndex = 14; pg.record.btnSave.onclick = pg.updateRecord_Request; pg.record.btnSave.title = "Save changes to this record"; // RECORD UPDATE SUBWIN pg.recordUpdate = da.subWin_update; pg.recordUpdate.lblUpdatedBy = pg.recordUpdate.all.lblUpdatedBy; pg.recordUpdate.lblUpdateDTS = pg.recordUpdate.all.lblUpdateDTS; pg.recordUpdate.type = pg.recordUpdate.all.type; pg.recordUpdate.onsetDate = pg.recordUpdate.all.onsetDate; pg.recordUpdate.description = pg.recordUpdate.all.description; pg.recordUpdate.resolveDate = pg.recordUpdate.all.resolveDate; pg.recordUpdate.assessmentType = pg.recordUpdate.all.assessmentType; // -- "CLOSE" pg.recordUpdate.btnClose = pg.recordUpdate.all.btnClose; pg.recordUpdate.btnClose.tabIndex = 1; pg.recordUpdate.btnClose.onclick = pg.hideUpdateView; pg.recordUpdate.btnClose.title = "Close this sub-window"; // COMMENTS SUBWIN pg.recordComments = da.subWin_comments; pg.recordComments.comments = pg.recordComments.all.updateComments; pg.recordComments.comment

    Read the article

  • I want to convert NSString to NSDate but UIPickerView shows current date

    - by Ali
    I want to convert NSString to NSDate but UIPickerView shows current datedatePicker=[[UIDatePicker alloc]init]; datePicker.userInteractionEnabled=YES; datePicker.minuteInterval=5; NSLog(@"Date"); //////// NSString *curDate=alarmData.date; //Jan 14, 2011 11:37 NSDateFormatter *format = [[NSDateFormatter alloc] init]; [format setDateFormat:@"MMM dd, yyyy HH:mm"]; //Optionally for time zone converstions [format setTimeZone:[NSTimeZone timeZoneWithName:nil]]; NSDate *da = [format dateFromString:curDate]; [datePicker setDate:da animated:YES]; any suggestions

    Read the article

  • Silverlight 3 DataBinding with ValueConverter: conditionally use the default value for property

    - by eriksmith200
    I have a DatePicker for which I want to set the BorderBrush to SolidColorBrush(Colors.Red) if the SelectedDate is null. If a date has been filled in though, I want to just have the default BorderBrush. I still want to be able to style the default BorderBrush in Blend, so I don't want to hardcode the default borderbrush of the DatePicker. So basically: xaml: <controls:DatePicker BorderBrush="{Binding SelectedDate, RelativeSource={RelativeSource Self}, Converter={StaticResource BrushConverter}, Mode=OneWay}"/> c#: public class BrushConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { return value == null ? new SolidColorBrush(Colors.Red) : /* when value != null have the bound property use it's default value */ } is this possible?

    Read the article

  • insert a date in mysql database

    - by kawtousse
    I use a jquery datepicker then i read it in my servlet like that: String dateimput=request.getParameter("datepicker");//1 then parse it like that: System.out.println("datepicker:" +dateimput); DateFormat df = new SimpleDateFormat("MM/dd/yyyy"); java.util.Date dt = null; try { dt = df.parse(dateimput); System.out.println("date imput parssé1 est:" +dt); System.out.println("date imput parsée2 est:" +df.format(dt)); } catch (ParseException e) { e.printStackTrace(); } and insert query like that: String query = "Insert into dailytimesheet(trackingDate,activity,projectCode) values ("+df.format(dt)+", \""+activity+"\" ,\""+projet+"\")"; it pass successfully untill now but if i check the record inserted i found the date: 01/01/0001 00:00:00 l've tried to fix it but it still a mess for me.

    Read the article

  • Issue with android tablayout switch tab

    - by user330915
    I am a new android developer, just tried something with Android Tablayout. There are two tabs and one tab has a GridView and the other one has a DatePicker. I created an activity and layout for each tab. The problem is that when I switch to the gridView, the background is not refreshed, and the images are just drawn over the DatePicker, so through images, the DatePicker still can be seen. It really bothers me. What should I do to have a clean background for imageView? Steve

    Read the article

  • UIDatePicker locale does nothing?

    - by morticae
    I'm creating a UIDatePicker programmatically, and setting its locale with the following code: datePicker.locale = [[[NSLocale alloc] initWithLocaleIdentifier:@"es_ES"] autorelease]; The datepicker still appears in English (or whatever language I've set the phone to). Anyone have any idea why this does nothing, or how to fix it?

    Read the article

  • jQuery UI not binding on popup windows

    - by Seth Duncan
    I get my datepicker control to bind fine to anything with a class of calendarTrigger on any of my pages, however on Popups (Of which use a Master Page and have the script files on it's master page) they don't bind to trigger datepicker UI elements. Is there something I am missing ?

    Read the article

  • Problem in type casting in NSDate to NSString?

    - by Prash.......
    Hi, I developing an application, in which i found a ridiculous problem in type casting, I am not able to type cast NSDate to NSString. NSDate *selected =[datePicker date]; NSString *stringTypeCast = [[NSString alloc] initWithData:selected encoding:NSUTF8StringEncoding]; From ,above snippet datePicker is an object of UIDatePickerController.

    Read the article

  • setting the datetime in jquery datetime picker with database datetime.

    - by sagar
    hi,i am developing a multi language site.My problem is i need to set the date and time in the datepicker from the database as the user may have choose the different timezone while registering in the site.At present i am getting the server time on my jquery datepicker. Thanks in advance. Technology used:Asp.net mvc,Jquery. Database:Sql server2005. O/s :winxp.

    Read the article

  • How to load jqueryui from google CDN with locale different than english?

    - by WooYek
    I would like load a different than English language locale for jqueryui, while loading jqueryui form Google AJAX Libraries API CDN? Is there a way to pass I18n parameter into load function? google.load("jqueryui", "1.7.2") I have also tried as per jQueryUI documentation on date picker internationalization to pass: $(selector).datepicker($.datepicker.regional['pl']); ... but it did not do the trick :(

    Read the article

  • Removing time from date format

    - by Prash.......
    Hi, I am developing an application in that i have used DatePicker to pick the date but it gives me date with time .I have converted that format into string, now i just want date from that. How should i do that.Plz suggest me something. Following is my code Snippet. NSDate *selected =[datePicker date]; NSString *dateString = [NSString stringWithFormat:@"%@", selected]; here date picker is object of UIDatePicker.

    Read the article

  • can i change the image place using jquery

    - by kumar
    I have jquery datepicker code where i am dispalying one calander control to dispaly dateand time $("input[id^='exc-flwup-<%=Model.ExceptionID%>']").datepicker({ duration: 0, buttonImage: '/Content/images/calender.gif', buttonImageOnly: true, showOn:'button', constrainInput: true, showTime: true, stepMinutes: 30, stepHours: 1, altTimeField: '', time24h: true, minDate: 0 }); Image button is allways coming left side of my textbox I need to keep it right side of my textbox is there any way I can adjust my image on this? thanks

    Read the article

  • which android event is called if i click on same item again and again?

    - by UMMA
    dear friends, i have created a "pick date" item text inside android spinner and written event onItemSelected to open datepicker dialog if user clicks on that perticular text. but the problem is if once date picker is opened i press cancel of datepicker dialog and then i try to re open it clicking on date picker text of spinner no event is called. can any one guide me what which event should i use ? any help would be appriciated.

    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

  • 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

  • List of blogs - year 2010

    - by hajan
    This is the last day of year 2010 and I would like to add links to all blogs I have posted in this year. First, I would like to mention that I started blogging in ASP.NET Community in May / June 2010 and have really enjoyed writing for my favorite technologies, such as: ASP.NET, jQuery/JavaScript, C#, LINQ, Web Services etc. I also had great feedback either through comments on my blogs or in Twitter, Facebook, LinkedIn where I met many new experts just as a result of my blog posts. Thanks to the interesting topics I have in my blog, I became DZone MVB. Here is the list of blogs I made in 2010 in my ASP.NET Community Weblog: (newest to oldest) Great library of ASP.NET videos – Pluralsight! NDepend – Code Query Language (CQL) NDepend tool – Why every developer working with Visual Studio.NET must try it! jQuery Templates in ASP.NET - Blogs Series jQuery Templates - XHTML Validation jQuery Templates with ASP.NET MVC jQuery Templates - {Supported Tags} jQuery Templates – tmpl(), template() and tmplItem() Introduction to jQuery Templates ViewBag dynamic in ASP.NET MVC 3 - RC 2 Today I had a presentation on "Deep Dive into jQuery Templates in ASP.NET" jQuery Data Linking in ASP.NET How do you prefer getting bundles of technologies?? Case-insensitive XPath query search on XML Document in ASP.NET jQuery UI Accordion in ASP.NET MVC - feed with data from database (Part 3) jQuery UI Accordion in ASP.NET WebForms - feed with data from database (Part 2) jQuery UI Accordion in ASP.NET – Client side implementation (Part 1) Using Images embedded in Project’s Assembly Macedonian Code Camp 2010 event has finished successfully Tips and Tricks: Deferred execution using LINQ Using System.Diagnostics.Stopwatch class to measure the elapsed time Speaking at Macedonian Code Camp 2010 URL Routing in ASP.NET 4.0 Web Forms Conflicts between ASP.NET AJAX UpdatePanels & jQuery functions Integration of jQuery DatePicker in ASP.NET Website – Localization (part 3) Why not to use HttpResponse.Close and HttpResponse.End Calculate Business Days using LINQ Get Distinct values of an Array using LINQ Using CodeRun browser-based IDE to create ASP.NET Web Applications Using params keyword – Methods with variable number of parameters Working with Code Snippets in VS.NET  Working with System.IO.Path static class Calculating GridView total using JavaScript/JQuery The new SortedSet<T> Collection in .NET 4.0 JavaScriptSerializer – Dictionary to JSON Serialization and Deserialization Integration of jQuery DatePicker in ASP.NET Website – JS Validation Script (part 2) Integration of jQuery DatePicker in ASP.NET Website (part 1) Transferring large data when using Web Services Forums dedicated to WebMatrix Microsoft WebMatrix – Short overview & installation Working with embedded resources in Project's assembly Debugging ASP.NET Web Services Save and Display YouTube Videos on ASP.NET Website Hello ASP.NET World... In addition, I would like to mention that I have big list of blog posts in CodeASP.NET Community (total 60 blogs) and the local MKDOT.NET Community (total 61 blogs). You may find most of my weblogs.asp.net/hajan blogs posted there too, but there you can find many others. In my blog on MKDOT.NET Community you can find most of my ASP.NET Weblog posts translated in Macedonian language, some of them posted in English and some other blogs that were posted only there. By reading my blogs, I hope you have learnt something new or at least have confirmed your knowledge. And also, if you haven't, I encourage you to start blogging and share your Microsoft Tech. thoughts with all of us... Sharing and spreading knowledge is definitely one of the noblest things which we can do in our life. "Give a man a fish and he will eat for a day. Teach a man to fish and he will eat for a lifetime" HAPPY NEW 2011 YEAR!!! Best Regards, Hajan

    Read the article

< Previous Page | 8 9 10 11 12 13 14 15 16 17 18 19  | Next Page >