JavaScript Snippets

  1. Write A Cookie
  2. Switch Source of Window
  3. Difference between two dates
  4. Conditional Operator
  5. Form Select Box Values
  6. Child Windows
  7. Random Number
  8. Switch Statement
  1. Write A Cookie

    function writeCookie(name, value) { 
       // Write out cookie of with 90 expiry date
       
       var expdate = new Date()
       expdate.setTime (expdate.getTime() + 90*(24 * 60 * 60 * 1000)) 
       document.cookie = name+"="+value+";expires=" + expdate.toUTCString();
    }
    
  2. Switch Source of window

       window.location.replace('newFile.asp');
    
  3. Difference between two dates

    
       startYear = "2001"
       startMonth = "1"��� //---> ==FEBRUARY
       startDay = "1"����� //---> == 1
       endYear = "2002"
       endMonth = "2"���   //---> ==MARCH
       endDay = "26"�����  //---> == 1
    
       var startDate = new Date (startYear,startMonth,startDay)
       var endDate = new Date (endYear,endMonth,endDay)
    
       var startms = startDate.getTime();
       var endms = endDate.getTime();
    
       var difference = endms - startms;
       var daysdifference = difference/1000/60/60/24;
    
    
  4. Conditional Operator

       x = (expression) ? value1 : value2 
       
       x = value1 if expression true 
       x = value2 if expression false 
    
  5. Form Select Box Values

    <SCRIPT> function sbmt(aform) { alert (aform.sel.options[aform.sel.selectedIndex].value ) return true; } </SCRIPT> <form name="frm" action="http://www.geocities.com/paulrowland2000/Dev/xx.asp" onSubmit="return sbmt(this)"> <select name="sel"> <option value="11111">111111111111 <option value="22222">2222222222222 <option value="33333">333333333333 <option value="44444">4444444444 </select> <input type=submit value=submit id=submit1 name=submit1> </form>
  6. Child Windows

    in the main window
        var bReload = true;
        xxx = window.open('aURL','aName')
        window.xxx.hello
         
    in the window thats opened
        alert(this.opener.bReload)
        function hello () {
         alert ('hello')
        }
    
  7. Random Number

    
     If you need random floating-point numbers
     in the range from A to B, use this code: 
    
     num is random, from A to B 
    
     num = A + (B-A)*Math.random()  
    
    
  8. Switch Statement

    switch sVarName {
    	case "selUniversityId":
            frmApprovedCourses.sCourse.value = '';
    		break;
    	case "selCourseId":
            frmApprovedCourses.sCourse.value = 'x';
    		break;
        default:
            break;   			
    	}
    


  9. 
    
    
Hosted by www.Geocities.ws

1