www.webdeveloper.com
Results 1 to 15 of 15

Thread: [RESOLVED] Onchange doesn't detect change on date field?

  1. #1
    Join Date
    Feb 2011
    Posts
    24

    resolved [RESOLVED] Onchange doesn't detect change on date field?

    Good evening/morning
    I have 2 fields - start date (pickupdate) and end date(dropoffdate) with a datepicker on both.
    When the user picks a start date I would like to change the end date automatically to start date+3 days.
    I added an onchange to my input field with a call of a javascript function

    Code:
    <input type="text" name="pickupdate" id="pickupdate" value="<?php echo htmlspecialchars($demain);?>"  maxlength="10" size="10" onchange="setExpDate()">
    I tried adding the 3 days in a function and nothing happened so I just created a text field and asked the function to write "test" in the text box when the pickup date is changed but even that doesn't work:

    Code:
    <script language="JavaScript1.2">
    function setExpDate()
      {  
        objForm.test.value = "test";
      };
    </script>
    I am obviously doing something glaringly wrong . Please could someone give me an indication of where I am going wrong?
    the website is www.carhirecappadocia.com and my complete script is below. Thank you in advance to anybody who could give me some advice.
    Code:
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html lang="en" >
    <head>
    
    <script src="../_frame/ui/jquery.ui.datepicker.min.js"></script>
    <script src="../_frame/ui/locales/jquery.ui.datepicker-en-GB.js"></script>
    <script src="../_frame/validate.js"></script>
    
    </head>
    
    <body>
    
    <!-- recuperer la date de demain par default pour le pick up -->
    <!-- rajouter 3 jours par default pour le dropoff -->
    <?php
    $demain = date("d/m/Y", mktime(0, 0, 0, date("m"), date("d")+1, date("Y")));
    $apres = date("d/m/Y", mktime(0, 0, 0, date("m"), date("d")+4, date("Y")));
    ?>
    
    <!-- Mettre la couleur de fond de page et d�finir la mise en page -->
    <style type="text/css"> 
    
    #back 
    {
      font: Arial, Helvetica, sans-serif; color: #FFFFFF;
      display: block;
      float: left;
      width: 280px;
      padding-bottom:5px;
      background: url(background_main.gif) top repeat-x #333333;
    }
      
    .searchbutton
    {
      text-align:center; color:#000000;  
      font-family:Arial, Helvetica, sans-serif; 
      font-size:14px;    
      font-weight:bold;
    }
    
    
    .label
    {
      text-align:left; color:#FFFFFF;  
      font-family:Arial, Helvetica, sans-serif; 
      font-size:14px;  
      position: relative;  
      margin-left: 20px;
    }
    
    </style>
    
    <script language="JavaScript1.2">
      function validateForm_bv000002( objForm )
      {
        if( objForm.pickupdate.value.length == 0 )
        {
          alert( "Field \"Pick Up Date\" is required !" );
          objForm.pickupdate.focus();
          return false;
        }
        if( objForm.pickupdate.value.length > 10 )
        {
          alert( "Field \"Pick Up Date\" is too long. 10 characters are allowed !" );
          objForm.pickupdate.focus();
          return false;
        }
        var df0 = validDate( objForm.pickupdate.value, "en-GB" );
        if( df0 != "" )
        {
          var s = "Field \"Pick Up Date\" must be a valid MM/DD/YYYY date !";
          df0 = df0.replace( "YY", "YYYY");
          s = s.replace( "DD/MM/YYYY", df0 ).replace( "MM/DD/YYYY", df0 );
          alert( s );
          objForm.pickupdate.focus();
          return false;
        }
         
        if( objForm.dropoffdate.value.length == 0 )
        {
          alert( "Field \"Drop Off Date\" is required !" );
          objForm.dropoffdate.focus();
          return false;
        }
        if( objForm.pickupdate.value.length > 10 )
        {
          alert( "Field \"Drop Off Date\" is too long. 10 characters are allowed !" );
          objForm.dropoffdate.focus();
          return false;
        }
        var df0 = validDate( objForm.dropoffdate.value, "en-GB" );
        if( df0 != "" )
        {
          var s = "Field \"Drop Off Date\" must be a valid MM/DD/YYYY date !";
          df0 = df0.replace( "YY", "YYYY");
          s = s.replace( "DD/MM/YYYY", df0 ).replace( "MM/DD/YYYY", df0 );
          alert( s );
          objForm.dropoffdate.focus();
          return false;
        }    
        objForm.pickupdate.value = convertDateToUserFormat( objForm.pickupdate.value, "en-GB", "dd/mm/yyyy" );
        objForm.dropoffdate.value = convertDateToUserFormat( objForm.dropoffdate.value, "en-GB", "dd/mm/yyyy" );    
        return true;
      }
    $(function(){
    $("#pickupdate").datepicker({changeMonth:true,changeYear:true,showAnim:"slideDown"});
    $("#dropoffdate").datepicker({changeMonth:true,changeYear:true,showAnim:"slideDown"});
    });
    </script>
    
    <script language="JavaScript1.2">
    function setExpDate()
      {  
        objForm.test.value = "test";
      };
    </script>
    
    <div id="back">
      <FORM NAME ="bv000002" METHOD ="POST" onsubmit="return validateForm_bv000002( this );" ACTION = "../ourfleet/index.php">
      
      <input type="hidden" name="copyright" value="Copyright � 2012 A E Teknoloji. All rights reserved. Unless otherwise indicated, all materials on these pages are copyrighted by AE Teknoloji. All rights reserved. No part of these pages, either text or image may be used for any purpose other than personal use. Therefore, reproduction, modification, storage in a retrieval system or retransmission, in any form or by any means, electronic, mechanical or otherwise, for reasons other than personal use, is strictly prohibited without prior written permission.  General inquiries should be directed to our Web feedback box, accessible from the link in the footer at the bottom of all pages on this site.">
        
      <div class="label">  
        Pick Up From: <font color="red"><sup style="cursor:help" title="Select a Pick Up Town!">*</sup></font><br /> 
        <select id="pickupfrom" name='pickupfrom'>    
        <option value="Urgup" selected>Urgup, Cappadocia</option>    
        <option value="Goreme">Goreme, Cappadocia</option>    
        <option value="Avanos">Avanos, Cappadocia</option>    
        <option value="Uchisar">Uchisar, Cappadocia</option>        
        <option value="Mustafapasa">Mustafapasa, Cappadocia</option>
        <option value="Kayseri">Kayseri Airport(ASR)</option>    
        <option value="Nevsehir">Nevsehir Airport(NAV)</option>    
        <option value="Istanbul">Istanbul</option>    
        <option value="Ankara">Ankara</option> 
        <option value="Other">Other</option>   
        </select> 
        <br /> 
      
        Drop Off: <font color="red"><sup style="cursor:help" title="Select a Drop Off Town !">*</sup></font><br /> 
        <select id="dropoff" name='dropoff'>    
        <option value="Same" selected>Same As Pick Up</option>
        <option value="Urgup">Urgup, Cappadocia</option>    
        <option value="Goreme">Goreme, Cappadocia</option>    
        <option value="Avanos">Avanos, Cappadocia</option>    
        <option value="Uchisar">Uchisar, Cappadocia</option>        
        <option value="Mustafapasa">Mustafapasa, Cappadocia</option>
        <option value="Kayseri">Kayseri Airport(ASR)</option>    
        <option value="Nevsehir">Nevsehir Airport(NAV)</option>    
        <option value="Istanbul">Istanbul</option>    
        <option value="Ankara">Ankara</option>        
        <option value="Other">Other</option>
        </select>     
        <br />    
    
        Pick Up Date: <font color="red"><sup style="cursor:help" title="Select a date !">*</sup></font><br /> 
        <input type="text" name="pickupdate" id="pickupdate" value="<?php echo htmlspecialchars($demain);?>"  maxlength="10" size="10" onchange="setExpDate()">    
        <input type="text" name="test" id="test" value="">
        <br />
            
        Drop Off Date: <font color="red"><sup style="cursor:help" title="Select a date !">*</sup></font><br /> 
        <input type="text" name="dropoffdate" id="dropoffdate" value="<?php echo htmlspecialchars($apres);?>" maxlength="10" size="10">  
        <br /> 
        
      </div>  
    
      <div class="searchbutton">
        <input type="Submit" Name="Submit1" value="Search">  
      </div>
      
    </FORM>
    </div>
    </body>
    </html>

  2. #2
    Join Date
    Nov 2010
    Posts
    1,100
    onchange fires on text inputs when the input loses focus (making the difference between it an onblur to me seem meaningless) - try entering something in your box and then clicking on another part of the page - the event should fire. If you want the value in the second box to appear as soon as the first box is filled (which I guess happens from the datepicker) you would have to find the function in the datepicker that fills the first box and get it to fill the second box at that time too. html5 has an oninput event that could help you here, but it is only supported by modern browsers

  3. #3
    Join Date
    Feb 2011
    Posts
    24
    Thank you so much for taking the time to look at this and reply!

    I think I am getting out of my depth here as it would mean getting into the entrails of the jquery ui datepicker script so I think I'll decide it will be a "nice to have" for a future date. I still have yet to struggle with the date validations (> today, start date < end date) and the difference in days between the 2 dates.
    Thank you again.

  4. #4
    Join Date
    Nov 2010
    Posts
    1,100
    hey, what happened to optimism? the datepicker has an onselect event...

    Code:
    <!doctype html>
     
    <html lang="en">
    <head>
        <meta charset="utf-8" />
        <title></title>
        <link rel="stylesheet" href="http://code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css" />
        <script src="http://code.jquery.com/jquery-1.8.3.js"></script>
        <script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
        <link rel="stylesheet" href="/resources/demos/style.css" />
        <script>
        $(function() {
            $( "#start" ).datepicker({
                onSelect: function(dateText, inst) { 
    			var dt=new Date(dateText)
    			var end=new Date()
    			end.setDate(dt.getDate()+3)
            $( "#fin" ).val(end.getMonth()+1+"/"+end.getDate()+"/"+end.getFullYear());
    					}
    			});
        });
        </script>
    </head>
    <body>
     
    <p>Date: <input type="text" id="start" />&nbsp;<input type="text" id="fin" size="30" /></p>
     
     
    </body>
    </html>

  5. #5
    Join Date
    Nov 2010
    Posts
    1,100
    there is also a min date restriction:
    http://jqueryui.com/datepicker/#min-max

    which you can use to make sure it is today or further into the future.

    Calculating the days between two dates is easily done with the javascript Date object - you can google it and post back if you get stuck

  6. #6
    Join Date
    Feb 2011
    Posts
    24
    Thank you for the encouragement, I'm definitely a bit lost and have just started looking at the moment.js library but I'll try to take things one at a time and work it out for myself before bothering you with more posts.

  7. #7
    Join Date
    Nov 2010
    Posts
    1,100
    here, this might help you along:
    Code:
    <!doctype html>
    <html lang="en">
    <head>
        <meta charset="utf-8" />
        <title></title>
        <link rel="stylesheet" href="http://code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css" />
        <script src="http://code.jquery.com/jquery-1.8.3.js"></script>
        <script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
    </head>
    <body>
    <p>Date: <input type="text" id="start" />&nbsp;<input type="text" id="fin" size="30" /></p>
    <div id="res"></div>
    <script>
        $(function() {
    	function getDiff(){
    	var a=new Date($("#start").val());
    	var b=new Date($("#fin").val());
    	var diff=b-a;
    	var days=diff/86400000;
    	$("#res").text(days+ " days difference")
    	}
    	
            $("#start").datepicker({
    		minDate:0,
                onSelect: function(dateText, inst) { 
    			var dt=new Date(dateText)
    			var end=new Date();
    			end.setDate(dt.getDate()+3)
            $( "#fin" ).val(end.getMonth()+1+"/"+end.getDate()+"/"+end.getFullYear());
    		getDiff();
    					}
    			});
    		$("#fin").datepicker({
    		minDate:new Date($("#start").val())+3,
                onSelect: getDiff
    			});	
        });
        </script>
    </body>
    </html>

  8. #8
    Join Date
    Nov 2010
    Posts
    1,100
    oops. small error with the minDate setting on the second box:
    Code:
    <script>
        $(function() {
    	function getDiff(){
    	var a=new Date($("#start").val());
    	var b=new Date($("#fin").val());
    	var diff=b-a;
    	var days=diff/86400000;
    	$("#res").text(days+ " days difference")
    	}
    	
    	 $("#start").datepicker({
    		minDate:0,
                onSelect: function(dateText, inst) { 
    			var dt=new Date(dateText)
    			var end=new Date();
    			end.setDate(dt.getDate()+3)
            $( "#fin" ).val(end.getMonth()+1+"/"+end.getDate()+"/"+end.getFullYear());
    		$( "#fin" ).datepicker( "option", "minDate", end);
    		getDiff();
    					}
    			});
    		$("#fin").datepicker({
                onSelect: getDiff
    			});	
        });
        </script>

  9. #9
    Join Date
    Nov 2012
    Location
    Jakarta
    Posts
    42

    You need to pass the parameter to the function

    You need to pass the parameter to the function.

    Inside the function setExpDate(), objform is "undefined".

    Try put the line

    Code:
    alert(objform);
    inside the function to help you debug the problem.

  10. #10
    Join Date
    Feb 2011
    Posts
    24
    Thank you for your help but I may be a lost cause!

    I have tried to adapt it but can't get it to work. (www.carhirecappadocia.com to see results)

    I created a field res:
    Code:
    <input type="text" name="res" id="res">
    I added your function My dates are in GB format dd/mm/YYYY so maybe this is the problem?
    This is what I inserted, I tried to space it out so as to try and undersatnd what I am doing:

    Code:
    $(function() 
     {
            function getDiff()
            {
                var a=new Date($("#pickupdate").val());
                var b=new Date($("#dropoffdate").val());
                var diff=b-a;
                var days=diff/86400000;
                $("#res").text(days+ " days difference")
    	}
    
    	$("#pickupdate").datepicker(
            {
                changeMonth:true,changeYear:true,showAnim:"fadeIn",gotoCurrent:true, minDate:0,
                onSelect: function(dateText, inst) 
                {
                    var dt=new Date(dateText)
                    var end=new Date();
    	        end.setDate(dt.getDate()+3)
                    $( "#dropoffdate" ).val(end.getDate()+"/"+end.getMonth()+1+"/"+end.getFullYear());
    		$( "#dropoffdate" ).datepicker("option", "minDate", end);
    		getDiff();
                }
    	});        
            
    	$("#dropoffdate").datepicker(
            {
                changeMonth:true,changeYear:true,showAnim:"fadeIn",
                onSelect: getDiff
            });	
     });
    When I select the first date the second one goes blank and when I select the second one, it posıtions on 15/12/2012 and no days different show.
    Sorry for being thick!
    Last edited by Optimistic; 12-26-2012 at 05:19 AM.

  11. #11
    Join Date
    Feb 2011
    Posts
    24
    I've done a bit more playing around with the script and patchworked some other bits in and I think I am nearly there:
    Code:
     $(function() 
     {
            function getDiff()
            {
            var from = document.getElementById("pickupdate").value;        
            var till = document.getElementById("dropoffdate").value;        
            // calculer nombre jours difference
            var c = from.split("/");
            start = new Date(c[2],c[1],c[0]);        
            var d = till.split("/");
            end = new Date(d[2],d[1],d[0]);        
            var rest = (end - start)/86400000; 
            $("#res").val(rest);       
            }
    
    	$("#pickupdate").datepicker(
            {
                changeMonth:true,changeYear:true,showAnim:"fadeIn",gotoCurrent:true, minDate:0,
                onSelect: function(dateText, inst) 
                { 
                   var c= $(this).val().split("/")                
                   if(c.length==3) 
                   { 
                      var date=new Date(c[2],c[1],c[0]);                   
                      $("#dropoffdate").val(date.getDate()+3+"/"+date.getMonth()+"/"+date.getFullYear());
                      objForm.dropoffdate.value = convertDateToUserFormat( objForm.dropoffdate.value, "en-GB", "dd/mm/yyyy" );                   
                      getDiff();
                   }
                } 
    	});        
            
    	$("#dropoffdate").datepicker(
            {
                changeMonth:true,changeYear:true,showAnim:"fadeIn",
                onSelect: getDiff
            });	
     });
    But I still have some issues:
    - if pickupdate is 28/12/2012 dropoffdate becomes 31/0/2013
    - the pickupdate datepicker window doesn't close when the date is picked
    - the number of days difference doesn't always re-caclulate
    Any ideas where I am going wrong?(www.carhirecappadocia.com)
    Thank you for your patience.

  12. #12
    Join Date
    Nov 2010
    Posts
    1,100
    I think this might be it. If you're going to keep working on this you should really have a look at the API - there are alot of builtin methods there (like dateFormat) which will save you time.

    I am assuming that you want the dropoff field to have a minimum date three days from the date chosen in the pickup field - if not, see comments in the code for how to change that

    Code:
    <script>
    $(function() 
     {
    		
            function getDiff()
            {
            var from = $("#pickupdate").val();        
            var till = $("#dropoffdate").val();        
            // calculer nombre jours difference
            var c = from.split("/");
            start = new Date(c[2],c[1],c[0]);        
            var d = till.split("/");
            end = new Date(d[2],d[1],d[0]);        
            var rest = (end - start)/86400000; 
            $("#res").val(rest);       
            }
    
    	$("#pickupdate").datepicker(
            {
                changeMonth:true,
    			changeYear:true,
    			showAnim:"fadeIn",
    			gotoCurrent:true, 
    			minDate:0,
    			dateFormat: "dd/mm/yy",
                onSelect: function(dateText, inst) 
                { 
                var dt=new Date(inst.selectedYear,inst.selectedMonth,inst.selectedDay)
    			var end=new Date();
    			end.setDate(dt.getDate()+3)
            $( "#dropoffdate" ).val(end.getDate()+"/"+(end.getMonth()+1)+"/"+end.getFullYear());
    		$( "#dropoffdate" ).datepicker( "option", "minDate", end); //delete this line if you don't want to set the min date 3 days from the date picked
    		getDiff();
                } 
    	});        
            
    	$("#dropoffdate").datepicker(
            {dateFormat: "dd/mm/yy",
    		//	minDate:0,   //uncomment this to make the min date today
                changeMonth:true,
    			changeYear:true,
    			showAnim:"fadeIn",
                onSelect: getDiff
            });	
     });
     </script>

  13. #13
    Join Date
    Feb 2011
    Posts
    24
    That is great -thank you!!!!!
    I just changed the minimum date to dt rather than end (I just wanted the default frop off date to be 3 days after the pick up but to be able to change up until same day as pick up but not before).
    Anyway., thank you again, that is really helpful and I've learned a lot rather than just copying snippets of code.

  14. #14
    Join Date
    Feb 2011
    Posts
    24
    Just updating the script because it was doing weird things between 28/02 and 04/03 for example. this one seems to work:
    Code:
            function getDiff()
            {
                var from = $("#pickupdate").val();        
                var till = $("#dropoffdate").val();        
                // calculer nombre jours difference
                var c = from.split("/");
                debut = new Date(c[2],c[1] - 1,c[0]);        
                var d = till.split("/");
                fin = new Date(d[2],d[1] - 1,d[0]);       
                var rest = (fin - debut)/86400000; 
                $("#res").val(rest);                               
            }

  15. #15
    Join Date
    Nov 2010
    Posts
    1,100
    I guess you're talking about these lines:
    Code:
     debut = new Date(c[2],c[1] - 1,c[0]);        
     fin = new Date(d[2],d[1] - 1,d[0]);
    which is a good point. the javascript date object uses months with a zero index (so January is 0, February is 1, etc) which is why you need to subtract one when you take a humanly-readable date and make it into a date object (and the reverse when you're going the other way).

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles