23

So here is the setup: I have two jquery datepickers, inside a jquery tab, inside a jquery modal dialog window:

\---/\---/\---/_______________
/                            /
\                            \
/  DATEPICKER1               /
\                            \
/  DATEPICKER2               /
\                            \
/                            /
\                            \
/____________________________/

The first datepicker functions normally, but when I try to click a date in the second datepicker it simply activates the first one. Did you follow that? :)

So to sum up, clicking a date in datepicker2 activates datepicker1.

I have no idea why this is happening - they have different ids and names, as outlined below.

To create the datepickers I'm just using:

$(function() {
    $("#datepicker1").datepicker();
    $("#datepicker2").datepicker();
});

The fields are simply:

<input type="text" id="datepicker1" name="datepicker1" value="" />
<input type="text" id="datepicker2" name="datepicker2" value="" />

I'm using jQuery v1.9.0 and jQueryui v1.10.0.

Any thoughts on this? As a caveat, I am unable to post actual code due to restrictions from my employer, but I can answer most questions if you need any clarification. Any and all help would be greatly appreciated!!

musicmunky
  • 331
  • 1
  • 2
  • 10
  • 23
    +1 for the ASCII art. – Adrian Thompson Phillips Apr 23 '13 at 12:44
  • can you remove `$("#datepicker2").datepicker();` and see what is happening, whether `datepicker2` still trigger datepicker – Arun P Johny Apr 23 '13 at 12:45
  • 1
    check if your are working on write copy of codes.... this shouldn't happen..:) – bipen Apr 23 '13 at 12:47
  • @bipen, I agree - I've used jquery many times in many sites and NEVER encountered a problem like this. Sadly I've checked to make sure I'm using the right files, right code, etc. – musicmunky Apr 23 '13 at 12:50
  • 2
    It should work just fine: http://jsfiddle.net/DpmeB/ – Antony Apr 23 '13 at 12:50
  • @ArunPJohny - there aren't any "onclick" events assigned to the text box, but I did what you requested. When you click in datepicker2 (without having a datepicker assigned) it does not activate the first datepicker. – musicmunky Apr 23 '13 at 12:51
  • 1
    as a sidenote upgrade to jquery 1.9.1 as tehre are lot of bug fixes – Arun P Johny Apr 23 '13 at 12:56
  • `$(function() { $("#datepicker1, #datepicker2").datepicker(); });` works for me in a fiddle – Mark Schultheiss Apr 23 '13 at 12:58
  • ok, if you select a date on the datepicker where is it applied in 1/2? also are you familiar with javascript breakpoints and debugging using it – Arun P Johny Apr 23 '13 at 13:18
  • as debugging step, i will suggest to add a [beforeShow](http://api.jqueryui.com/datepicker/#option-beforeShow) handler and add breakpoint inside it to see what is happening and start back tracing from there – Arun P Johny Apr 23 '13 at 13:20
  • @ArunPJohny - good idea, I'd forgotten about the beforeShow handler. I'll give that a shot and see what I can figure out. – musicmunky Apr 23 '13 at 13:23
  • as you can see here http://jsfiddle.net/fMD62/5/ it should not be a problem with jquery UI itself, you probably have something thats messing with your code. – mfreitas Apr 24 '13 at 02:02
  • What does you JavaScript console say? btw. you should really use a classname as picker not the id. You can also use the `type="date"` as defined in HTML5. – codingjoe May 02 '13 at 12:08
  • @John - why should I use a classname instead of the id? I'm not arguing, just curious. Also, the console was not helpful in this case, as no errors were being thrown. I tried debugging the code itself, but didn't see any issues during execution. Eventually I found the resolution I posted above. – musicmunky May 02 '13 at 12:15
  • @musicmunky Well an Id is the better identifier but you don't want to declare just one object to be a DatePicker but a range of elements. That's why we have classification in HTML. HTML5 really takes that to the next level introducing types like 'date' and 'datetime'. You can simply use the type and override and only add jquery behavior if the browser doesn't already implement its own. That is especially helpful on handhelds. – codingjoe May 02 '13 at 12:22
  • @John - I understand exactly what you're saying, and that's a very good point, especially when using multiple datepickers on the same page. Sadly in this case I can't rely on HTML5 (this is for an internal project, and many users will be viewing the site on *shudder* IE8). Your comment about id vs class is good though, and I'll remember that going forward. Thanks very much!!! :) – musicmunky May 02 '13 at 12:54

10 Answers10

9

UPDATE: It looks like the behavior described below was addressed in another stackoverflow question here:
Prevent jQuery UI dialog from setting focus to first textbox

Apologies for the "duplicate" question - if I had known this was the problem I would have figured it out quickly!!!

################################################################################

Well, the resolution is very simple, and perhaps someone can enlighten me as to why it works this way because I'm a bit clueless at the moment.

Here's what I did:
I added another two text input fields to the form (they were needed) and reordered the layout so that one of those new input fields was the "first" element (in the top-left corner), like so:

\---/\---/\---/_______________
/                            /
\                            \
/  TEXTFIELD1   DATEPICKER1  /
\                            \
/  TEXTFIELD2   DATEPICKER2  /
\                            \
/                            /
\                            \
/____________________________/

Suddenly the problem has vanished! However, I notice an interesting behavior:
When I select a date in EITHER datepicker, the cursor then immediately jumps back to the first text field. So if this were happening when I had the datepickers with no text fields, that behavior would mean that the cursor would immediately have jumped back to the first datepicker which could have cause the issue I was having.

Now, as to WHY it works this way I have no idea. I tried setting the tabindex parameters for the various textfields/datepickers but that didn't change the behavior.

Anyway, I appreciate the input from everyone who chimed in - this was a weird problem, but I'll never forget how to fix it now. Thanks everyone for your help!!

Community
  • 1
  • 1
musicmunky
  • 331
  • 1
  • 2
  • 10
  • Thanks for tracking down a solution and sharing it, I'm facing the exact same issue. Despite the disbelief I can verify this is occuring with jQuery 1.9.1 and jquery-ui 1.10.0. I think the main detail in reproducing the issue is to have two datepickers in a dialog (modal in my case) – STW Oct 10 '13 at 02:41
  • Your link helped me. Thanks. Tried to hook up datepickers on 2 fields, but fieldA had an "autofocus" on it. The datepicker on fieldA did not show up if I didn't click on another field. After removing the "autofocus," the datepicker on each field works correctly. – Ervi B Mar 04 '14 at 21:18
4

Try this friend: in your JS

 $(function() {   
       $( "#from" ).datepicker({   
      defaultDate: "+1w",  
      changeMonth: true,   
      numberOfMonths: 1,  
      onClose: function( selectedDate ) {  
        $( "#to" ).datepicker( "option", "minDate", selectedDate );  
      }  
    });  
    $( "#to" ).datepicker({
      defaultDate: "+1w",
      changeMonth: true,
      numberOfMonths: 1,
      onClose: function( selectedDate ) {
        $( "#from" ).datepicker( "option", "maxDate", selectedDate );
      }
    });  
  });  
  
 <link rel="stylesheet" href="//code.jquery.com/ui/1.11.1/themes/smoothness/jquery-ui.css"/>
 <script src="//code.jquery.com/jquery-1.10.2.js"></script>
  <script src="//code.jquery.com/ui/1.11.1/jquery-ui.js"></script>
Start date: <input type="text" id="from" name="from"> 
End date: <input type="text" id="to" name = "to">

In your input

Start date: input type="text" id="from" name="from"

End date: input type="text" id="to" name = "to"

This worked for me :)

by MacElie M.

McElie
  • 140
  • 3
  • 12
2

I think you have another code that interfere with the javascript as this : http://jsfiddle.net/fMD62/

works perfectly (with jquery 1.9.1 and jqueryui 1.9.2

maybe try

$(function() {
    $("#datepicker1,#datepicker2").datepicker();
});
  • 1
    Thanks for the reply - sadly it didn't work. However, I do agree that there must be SOMETHING that is interfering with the jquery. I'm still hunting through the code trying to find that conflict. – musicmunky Apr 23 '13 at 12:57
2

This is a total shot in the dark but have you tried initialising each one seperately? Something like the following

$(function() {
    $('.datepicker').each(function(){
        $(this).datepicker();
    });
});

It's probably what the others have mentioned and you are encountering some form of interference with your code, but it's worth a quick shot.

1

On your example both datepickers have different id's and name's, however, the problem you describe is exactly what'll happen if you use the same name for both.

Does your actual code use different id and name for both datepickers?

Bardo
  • 2,470
  • 2
  • 24
  • 42
  • Both fields have different names/ids, and I've even gone so far as to make sure they are using different CSS classes (I know it shouldn't matter, but I'm just trying anything I can think of at this point). – musicmunky Apr 30 '13 at 11:43
1

Case 1:
@antony's comment(including jsfiddle link below the question) works as of
version jquery-1.9.1 and 1.9.2/jquery-ui.js

Case 2:
OP's case where datepicker1 works well but choosing datepicker2 will open datepicker1
version: jQuery v1.9.0 and jQueryui v1.10.0

Case 3:
My case where choosing datepicker1 works well but choosing datepicker2 has no any effect.
version: jquery-3.1.1.min.js and jQueryui v1.12.1

Case 3 solution:
initialize date1 first $('date1').datepicker() date1 will works
For date2, first destroy date1 then initialize date2

$('date1').datepicker('destroy');
$('date2').datepicker();

Now for date1, destroy date2 and initialize date1.

vusan
  • 5,221
  • 4
  • 46
  • 81
0

Try putting the contents of the JQuery UI Dialog into an IFrame. That might help you get around some of your issues.

\---/\---/\---/_______________
/                            /
\  ####IFRAME######          \
\  #              #          \
/  #DATEPICKER1   #          /
\  #              #          \
/  #DATEPICKER2   #          /
\  #              #          \
/  ################          /
\                            \
/____________________________/
Robert Bolton
  • 667
  • 3
  • 8
  • 22
  • 3
    I tend to avoid using iframes in general, and for this particular page I'm not allowed to use them at all (security issues). – musicmunky Apr 30 '13 at 11:44
0

EXPLANATION of issue

I have the same issue and its very disappointing. I searched through the source code of jquery and found this:

if ( $.ui.dialog.overlayInstances ) {
    this._on( this.document, {
        focusin: function( event ) {
            if ( !$( event.target ).closest(".ui-dialog").length ) {
                event.preventDefault();
                $(".ui-dialog:visible:last .ui-dialog-content")
                    .data("ui-dialog")._focusTabbable();
            }
        }
    });
}

So when you set focus in element thats not inside the .ui-dialog, it will trigger _focusTabbable() function which set focus to the first input in dialog.

The problem is, that $.datepicker creates div on the end of body - so it is outside of .ui-dialog

If there is another input which _focusTabbable() will give focus its ok, as datepicker can handle that. But if this input has datepicker binded, it will close the previous datepicker, open another on the first input and the select on the previous datepicker is not fired.

One of possible solutions

The solution is in this case have input wich will take first focus in dialog and does not have datepicker on it.

I simply use this HTML code as first input on begin of dialog content where otherwise datepicker input will be on first place:

<span class="ui-helper-hidden-accessible"><input type="text" /></span>
Gh61
  • 9,222
  • 4
  • 28
  • 39
0

Just to preface, I am a backend database programmer so know little about JavaScript so looked to find this post with the exact same question. Gleaning from what I read above and comparing to my existing code, I modified my JavaScript so that it works and thought I would share it.

The only caveat was that my existing forms with single date selectors no longer worked so I had to add a bit to handle those and all seem fine now. In this case, the database fields are actually a Unix timestamp so the form gets processed when submitted with the two fields converted as needed but for clarity, I did not include that code here.

$(document).ready(function(){ 
       $( "#StartDate" ).datepicker({   
                                altField: '#datepicker',
                                altFormat: 'yy-mm-dd',
                                dateFormat: 'D M d, yy', 
                                firstDay: 1,
      onClose: function( selectedDate ) {  
        $( "#StartDate" ).datepicker( "option", "minDate", selectedDate );  
      }  
    });  
    $( "#EndDate" ).datepicker({
                                altField: '#datepicker',
                                altFormat: 'yy-mm-dd',
                                dateFormat: 'D M d, yy', 
                                firstDay: 1,
      onClose: function( selectedDate ) {
        $( "#EndDate" ).datepicker( "option", "maxDate", selectedDate );
      }
    }); 
        $( "#datepicker" ).datepicker({
                                altField: '#datepicker',
                                altFormat: 'yy-mm-dd',
                                dateFormat: 'D M d, yy', 
                                firstDay: 1,
      onClose: function( selectedDate ) {
        $( "#datepicker" ).datepicker( "option", "maxDate", selectedDate );
      }
    });     
  });
DonP
  • 725
  • 1
  • 8
  • 27
-1

in a js archive:

$("#fecha_1").datepicker({
    dateFormat: "dd/mm/yy",
    dayNames: "Domingo Lunes Martes Miercoles Jueves Viernes Sabado".split(" "),
    dayNamesMin: "Do Lu Ma Mi Ju Vi Sa".split(" "),
    dayNamesShort: "Do Lu Ma Mi Ju Vi Sa".split(" "),
    monthNames: "Enero Febrero Marzo Abril Mayo Junio Julio Agosto Septiembre Octubre Noviembre Diciembre".split(" "),
    monthNamesShort: "Ene Feb Mar Abr May Jun Jul Ago Sep Oct Nov Dic".split(" "),
    prevText: "Ant",
    nextText: "Sig",
    currentText: "Hoy",
    changeMonth: !0,
    changeYear: !0,
    showAnim: "slideDown",
    yearRange: "1900:2100"
});

$("#fecha_2").datepicker({
    dateFormat: "dd/mm/yy",
    dayNames: "Domingo Lunes Martes Miercoles Jueves Viernes Sabado".split(" "),
    dayNamesMin: "Do Lu Ma Mi Ju Vi Sa".split(" "),
    dayNamesShort: "Do Lu Ma Mi Ju Vi Sa".split(" "),
    monthNames: "Enero Febrero Marzo Abril Mayo Junio Julio Agosto Septiembre Octubre Noviembre Diciembre".split(" "),
    monthNamesShort: "Ene Feb Mar Abr May Jun Jul Ago Sep Oct Nov Dic".split(" "),
    prevText: "Ant",
    nextText: "Sig",
    currentText: "Hoy",
    changeMonth: !0,
    changeYear: !0,
    showAnim: "slideDown",
    yearRange: "1900:2100"
}); 

in ur page: <input type="text" id="fecha_1"><input type="text" id="fecha_2">

manuel_m2
  • 45
  • 5
  • Yes, this is how it's currently setup. I know about all the various parameters I can set for each datepicker - that's not my question. – musicmunky Apr 30 '13 at 11:52