2015년 11월 2일 월요일

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 정규표현식을 이해하기 위한 테스트 클래스
 * . : 임의의 한 문자(필수)를 의미
 * ? : 바로 앞에 문자가 없거나 하나가 있음을 의미
 * * : 바로 앞에 문자가 없거나 하나이상 반복을 의미
 * + : 바로 앞에 문자가 하나 이상 반복을 의미
 * ^ : 문자열의 시작을 의미
 * [^] : ^이후의 괄호안 형식을 제외함을 의미
 * $ : 문자열의 끝을 의미
 * [] : []안의 형식 일치를 의미
 * {} : {}앞 문자열(혹은 문자) 반복 갯수를 의미
 * () : ()안의 내용을 하나의 묶음으로 사용함을 의미
 * | : or 연산을 의미
 * [0-9] : (부터 - 까지)의 숫자를 의미
 * [a-z] : (부터 - 까지)의 소문자를 의미
 * [a-zA-Z] : (부터 - 까지)의 대,소문자를 의미
 * \p(Alpha) : 대,소문자 알파벳을 의미
 * \p(Digit) : 숫자를 의미
 * \p{Alnum} : 대/소문자 알파벳, 숫자를 의미
 * \d : 숫자를 의미
 * \D : 숫자가 아닌 것을 의미
 * \s : 공백 문자를 의미
 * \S : 공백 문자가 아닌 나머지 문자를 의미
 * \w : 알파벳이나 숫자
 * \W : 알파벳이나 숫자를 제외한 문자
 * \ : 정규표현식 역슬래시(\)는 확장 문자. 역슬래시 다음에 일반 문자가 오면 특수문자로 취급하고 역슬래시 다음에 특수문자가 오면 그 문자 자체를 의미
 * (?i) : 앞 부분에 (?i)라는 옵션을 넣어주면 대소문자를 구분하지 않음
 *
 * 사용예
 * 1) 숫자만 : ^[0-9]*$
 * 2) 영문자만 : ^[a-zA-Z]*$
 * 3) 한글만 : ^[가-힣]*$
 * 4) 영어 & 숫자만 : ^[a-zA-Z0-9]*$
 * 5) E-Mail : ^[_a-z0-9-]+(.[_a-z0-9-]+)*@(?:\\w+\\.)+\\w+$            
 * 6) 휴대폰 : ^01(?:0|1|[6-9]) - (?:\d{3}|\d{4}) - \d{4}$
 * 7) 일반전화 : ^\d{2.3} - \d{3,4} - \d{4}$
 * 8) 주민등록번호 : \d{6} \- [1-4]\d{6}
 * 9) IP 주소 : ([0-9]{1,3}) \. ([0-9]{1,3}) \. ([0-9]{1,3}) \. ([0-9]{1,3})
 *
 */

/** @author
 * 정규표현식 이해를 하기 위해서 만들어 본 클래스입니다.
 * 여기 예제의 대부분은 http://www.java2go.net/java/java_regex.html 에서 참조했습니다.
 * 작성일자 : 2015.11.03
 */
public class RegExTest {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
RegExTest regExTest = new RegExTest();
regExTest.regEx01();
regExTest.regExMailIDCheck();
regExTest.regEx02();
regExTest.regEx03();
regExTest.regEx04();
regExTest.regEx05();
regExTest.regEx06();
}

/**
* Pattern 객체는 Perl 문법과 비슷한 형태로 정의된 정규표현식을 나타낸다.
* 문자열로 정의한 정규표현식은 사용되기전에 반드시 Pattern클래스의 인스턴스로 컴파일되어야 한다.
* 컴파일된 패턴은 Matcher객체를 만드는데 사용되며, Matcher객체는 임의의 입력문자열이 패턴에 부합되는지 여부를 판가름하는 기능을 담당.
*/
private void regEx01() {
//정규표현식 적용 a로 시작하며, a 다음 아무 문자 1개만, 마지막은 c로 끝남
String regex = "^a.c$";
System.out.println("regEx01-abc : " + "abc".matches(regex)); //true
System.out.println("regEx01-abbc : " + "abbc".matches(regex)); //false
System.out.println("regEx01-a*c : " + "a*c".matches(regex)); //true
System.out.println("regEx01-a1c : " + "a1c".matches(regex)); //true
System.out.println("regEx01-a1cc : " + "a1cc".matches(regex)); //false

Pattern p = Pattern.compile("a*b");
Matcher m = p.matcher("aaaaaab");
boolean b = m.matches();

if (b) {
System.out.println("match");
} else {
System.out.println("not match");
}
}

//Mail 주소 체크.
private void regExMailIDCheck() {
String regex = "^[_a-z0-9-]+(.[_a-z0-9-]+)*@(?:\\w+\\.)+\\w+$"; //소문자만 인식
System.out.println("test001@hotmail.com : " + "test001@hotmail.com".matches(regex)); //true
System.out.println("test001@bbb.co.kr : " + "test001@bbb.co.kr".matches(regex)); //true
System.out.println("test001@bbb : " + "test001@bbb".matches(regex)); //false
System.out.println("TEST001@BBB.CO.KR : " + "TEST001@BBB.CO.KR".matches(regex)); //false

regex = "^[_a-zA-Z0-9-]+(.[_a-zA-Z0-9-]+)*@(?:\\w+\\.)+\\w+$"; //대문자도 인식할 수 있도록 변경
System.out.println("test001@hotmail.com : " + "test001@hotmail.com".matches(regex)); //true
System.out.println("test001@bbb.co.kr : " + "test001@bbb.co.kr".matches(regex)); //true
System.out.println("test001@bbb : " + "test001@bbb".matches(regex)); //false
System.out.println("TEST001@BBB.CO.KR : " + "TEST001@BBB.CO.KR".matches(regex)); //true
System.out.println("test001@bbb!.com : " + "test001@bbb!.com".matches(regex)); //false
}

/**
* 문자열 치환하기
* appendReplacement 메소드는 일치하는 패턴이 나타날 때까지의 모든 문자들을 버퍼로 옮기고 찾아진 문자열 대신 교체 문자열로 채워 넣는다.
* appendTail 메소드는 캐릭터 시퀀스의 현재 위치 이후의 문자들을 버퍼에 복사해 넣는다.
*/
private void regEx02() {
Pattern p = Pattern.compile("cat");
Matcher m = p.matcher("one cat two cats in the yard");

StringBuffer sb = new StringBuffer();
while(m.find()) {
m.appendReplacement(sb, "dog");
}
m.appendTail(sb);
System.out.println(sb.toString());
}

/**
* 이메일 주소 유효검사
*/
private boolean isValidEmail(String email) {
Pattern p = Pattern.compile("^(?:\\w+\\.?)*\\w+@(?:\\w+\\.)+\\w+$");
Matcher m = p.matcher(email);
return m.matches();
}

/**
* 이메일 주소 유효성 테스트
*/
private void regEx03() {
String[] emails = {"test@abc.com", "a@.com", "abc@mydomain", "ABC@mydoamin.COM", "chungwan.park@mydomin.co.kr"};

for (int i = 0; i < emails.length; i++) {
if (isValidEmail(emails[i])) {
System.out.println(emails[i]);
}
}
}

/**
* HTML 태그 제거
*/
private String stripHTML(String htmlStr) {
Pattern p = Pattern.compile("<(?:.|\\s)*?>");
Matcher m = p.matcher(htmlStr);
return m.replaceAll("");
}

private void regEx04() {
String htmlStr = "<html><body><h1>Java2go.net</h1> <p>Linuxwan's Personal Workspace...</p></body></html>";
System.out.println(stripHTML(htmlStr));
}

/**
* HTML 링크 만들기
*/
private String linkedText(String sText) {
Pattern p = Pattern.compile("(http|https|ftp)://[^\\s^\\.]+(\\.[^\\s^\\.]+)*");
Matcher m = p.matcher(sText);

StringBuffer sb = new StringBuffer();
while(m.find()) {
m.appendReplacement(sb, "<a href='" + m.group() + "'>" + m.group() + "</a>");
}
m.appendTail(sb);

return sb.toString();
}

private void regEx05() {
String strText = "My linked URL is http://wans-devstory.blogspot.kr/search/label/Android.";
System.out.println(linkedText(strText));
}

/**
* 금지어 필터링 하기
*/
private String filterText(String sText) {
Pattern p = Pattern.compile("fuck|shit|개새끼", Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher(sText);

StringBuffer sb = new StringBuffer();
while(m.find()) {
m.appendReplacement(sb, maskWord(m.group()));
}
m.appendTail(sb);

return sb.toString();
}

private String maskWord(String word) {
StringBuffer buff = new StringBuffer();
char[] ch = word.toCharArray();
for (int i = 0; i < ch.length; i++) {
if (i < 1) {
buff.append(ch[i]);
} else {
buff.append("*");
}
}
return buff.toString();
}

private void regEx06() {
String sText = "Shit! Read the fucking manual. 개새끼야.";
System.out.println(filterText(sText));
}
}

2015년 9월 7일 월요일

jQuery UI의 tab을 동적으로 생성하는 방법

jQuery UI의 tab을 동적으로 생성하는 방법.

$(function() {
$('#main_tab').tabs();
});

tab을 생성하는 함수.
function fn_tabAdd() {
no++;
var tabs = $("#main_tab").tabs();
var ul = tabs.find("ul");

$("<li><a href='#tabs-" + no + "'>" + "Tab No." + no + "</a></li>").appendTo(ul);
$("<div id='" + "tabs-" + no + "'>" + "Tabs No." + no + "</div>" ).appendTo(tabs);
tabs.tabs("refresh");
}

html파일.
..
<div id="main_tab">
<ul id="tab_head">
<li><a href="#tabs-0">Tab 1</a></li>
</ul>
<div id="tabs-0">Tab 01</div>
</div>
..

2015년 3월 18일 수요일

파이썬 프로그래밍 - Chapter 03

string.py


fred = "Why do gorillas have big nostrils? Big fingers!!"
print (fred)

fred = 'Why do gorillas have big nostrils? Big fingers!!'
print (fred)

fred = '''How do dinosaurs pay their bills?
With tyrannosaurus checks!'''
print (fred)

silly_string = '''He said, "Aren't can't shouldn't wouldn't."'''
print (silly_string)

#escape
single_quote_str = 'He said, "Aren\'t can\'t shouldn\'t wouldn\'t."'
print (single_quote_str)

double_quote_str = "He said, \"Aren't can't shouldn't wouldn't.\""
print (double_quote_str)

myscore = 1000
message = 'I scored %s points'
print (message % myscore)

#placeholder
nums = 'What did the number %s say to the number %s? Nice belt!!'
print (nums % (0, 8))

myletter.py


spaces = ' ' * 25
print('%s 12 Butts Whnd' % spaces)
print('%s Twinklebottom Heath' % spaces)
print('%s West Snoring' % spaces)
print('')
print('')
print('Dear Sir')
print('')
print('I wish to report that tiles are missing from the')
print('outside toilet roof.')
print('I think it was bad wind the other night that blew them away.')
print('')
print('Regards')
print('Malcolm Dithering')

List.py


wizard_list = 'spider legs, toe of frog, eye of newt, bat wing, slug butter, snake dandruff'
print(wizard_list)

wizard_list = ['spider legs', 'toe of frog', 'eye of newt', 'bat wing', 'slug butter', 'snake dandruff']
print(wizard_list)
print(wizard_list[2])

wizard_list[2] = 'snail tongue'
print(wizard_list)
print(wizard_list[2:5])

some_numbers = [1, 2, 5, 10, 20]
print(some_numbers)

some_things = ['Which', 'Witch', 'Is', 'Which']
print(some_things)

number_and_strings = ['Why', 'was', 6, 'afraid', 'of', 7, 'because', 7, 8, 9]
print(number_and_strings)

numbers = [1, 2, 3, 4]
strings = ['I', 'kicked', 'my', 'toe', 'and', 'it', 'is', 'sore']
mylist= [numbers, strings]
print(mylist)

wizard_list.append('bear burp')
print(wizard_list)

wizard_list.append('mandrake')
wizard_list.append('hemlock')
wizard_list.append('swamp gas')

print(wizard_list)

del wizard_list[5]
print(wizard_list)

del wizard_list[8]
del wizard_list[7]
del wizard_list[6]
print(wizard_list)

list1 = [1, 2, 3, 4]
list2 = ['I', 'tripped', 'over', 'and', 'hit', 'the', 'floor']
print(list1 + list2)
list3 = list1 + list2
print(list3)

list1 = [1, 2]
print(list1 * 5)

#tuple
fibs = (0, 1, 1, 2, 3)
fibs2 = (4, 5, 6, 7, 8)
print(fibs[3])
print(fibs * 2)
print(fibs + fibs2)

#map
favorite_sports = {'Ralph Williams' : 'Football',
                   'Michael Tippett' : 'Basketball',
                   'Edward Elgar' : 'Baseball',
                   'Rebecca Clarke' : 'Netball',
                   'Ethel Smyth' : 'Badminton',
                   'Frank Bridge' : 'Rugby'}
print(favorite_sports['Rebecca Clarke'])

del favorite_sports['Ethel Smyth']
print(favorite_sports)

favorite_sports['Ralph Williams'] = 'Ice Hockey'
print(favorite_sports)

파이썬 프로그래밍 - Chapter 02

variable.py


found_coins = 20
magic_coins = 10
stolen_coins = 3
msg = "found_coins + magic_coins * 365 - stolen_coins * 52 = %s"
sum = found_coins + magic_coins * 365 - stolen_coins * 52
print (msg % sum)

stolen_coins = 2
sum = found_coins + magic_coins * 365 - stolen_coins * 52
print (msg % sum)

magic_coins = 13
sum = found_coins + magic_coins * 365 - stolen_coins * 52
print (msg % sum)

2014년 12월 2일 화요일

C#으로 구현한 하위 폴더에서 특정 확장자의 파일 갯수를 카운트하는 프로그램.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.IO;
using System.Windows.Forms;

namespace FileCounter
{
    public partial class FileCounter : Form
    {
        private int counter = 0;

        public FileCounter()
        {
            InitializeComponent();
        }

        private void label1_Click(object sender, EventArgs e)
        {

        }

        private void txtFolderPath_TextChanged(object sender, EventArgs e)
        {

        }

        private void btnOpenFolderDlg_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog();
            folderBrowserDialog.SelectedPath = @"C\";

            if (folderBrowserDialog.ShowDialog() == DialogResult.OK)
            {
                txtFolderPath.Text = folderBrowserDialog.SelectedPath;
            }
        }

        private void btnFileCount_Click(object sender, EventArgs e)
        {
            //파일을 찾아야 폴더 선택 여부 확인
            if (txtFolderPath.Text == "" || txtFolderPath.Text.Length < 1)
            {
                MessageBox.Show("대상 폴더를 선택하세요. !!");
                return;
            }

            //찾아야 할 파일 확장자 입력 여부 확인
            if (txtFileExt.Text == "" || txtFileExt.Text.Length < 1)
            {
                MessageBox.Show("파일 확장자를 입력하세요. !!");
                return;
            }

            lbCount.Text = "";
            counter = 0;

            //Root폴더 아래의 파일 검색
            RootSearchFileExtCounter(txtFolderPath.Text, txtFileExt.Text);
            //하위 폴더 아래의 파일 검색
            DirSearchFileExtCounter(txtFolderPath.Text, txtFileExt.Text);
           
            lbCount.Text = "" + counter;          
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            //종료
            this.Close();
        }

        //Root폴더 아래의 파일을 검색
        void RootSearchFileExtCounter(string sDir, string sExt)
        {
            //입력된 파일 확장자에서 순수한 확장자만 추출
            string strExt = sExt;
            if (sExt.IndexOf("*") > -1) strExt = strExt.Replace("*", "");
            if (sExt.IndexOf(".") > -1) strExt = strExt.Replace(".", "");

            //검색을 위한 패턴 생성
            string searchPattern = "*." + strExt;

            string[] rootFileEntries = Directory.GetFiles(sDir, searchPattern);
            foreach (string rootFileName in rootFileEntries)
            {
                //순수 확장자가 파일명의 끝에 있는지 체크해서 카운트.
                if (rootFileName.EndsWith(strExt))
                {
                    counter = counter + 1;
                }
            }
        }

        void DirSearchFileExtCounter(string sDir, string sExt)
        {
            string strExt = sExt;
            if (sExt.IndexOf("*") > -1) strExt = strExt.Replace("*", "");          
            if (sExt.IndexOf(".") > -1) strExt = strExt.Replace(".", "");          

            string searchPattern = "*." + strExt;

            try
            {              
                //Root폴더 아래의 하위 폴더 갯수 만큼 Looping
                foreach (string d in Directory.GetDirectories(sDir))
                {
                    //searchPattern에 맞는 파일 목록을 가져온다.
                    string[] searchFileEntries = Directory.GetFiles(d, searchPattern);
                    //가져온 파일 목록만큼 Looping
                    foreach (string sFileName in searchFileEntries)
                    {
                        //순수 확장자가 파일명의 끝에 있는지 체크해서 카운트.
                        if (sFileName.EndsWith(strExt))
                        {
                            counter = counter + 1;
                        }
                    }
                    //하위 폴더 검색을 위한 재귀호출
                    DirSearchFileExtCounter(d, searchPattern);
                }
            }
            catch (System.Exception excpt)
            {
                Console.WriteLine(excpt.Message);
            }          
        }
    }
}

2014년 9월 11일 목요일

Full Calendar 사용법 예시.
좀 더 기능을 추가해서 완성도 높은 소스를 제공할 예정이다.

<!DOCTYPE html>
<html>
<title>Full Calendar Example</title>
<head>
<meta charset='utf-8' />
<link rel="stylesheet" href="http://code.jquery.com/ui/1.11.1/themes/smoothness/jquery-ui.css">
<link href='../css/fullcalendar.css' rel='stylesheet' />
<link href='../css/fullcalendar.print.css' rel='stylesheet' media='print' />
<style>
    label, input { display:block; }
    input.text { margin-bottom:12px; width:95%; padding: .4em; }
    fieldset { padding:0; border:0; margin-top:10px; }
    textarea { width:95%; overflow:visible;}
    h1 { font-size: 1.2em; margin: .6em 0; }
    div#users-contain { width: 350px; margin: 20px 0; }
    div#users-contain table { margin: 1em 0; border-collapse: collapse; width: 100%; }
    div#users-contain table td, div#users-contain table th { border: 1px solid #eee; padding: .6em 10px; text-align: left; }
    .ui-dialog .ui-state-error { padding: .3em; }
    .validateTips { border: 1px solid transparent; padding: 0.3em; }
</style>
 
<script src='../js/moment.min.js'></script>
<script src='../js/jquery.min.js'></script>
<script src='http://code.jquery.com/ui/1.11.1/jquery-ui.js'></script>
<script src='../js/fullcalendar.min.js'></script>
<script src='../js/lang-all.js'></script>
<script>
var dialog, form;
var timeList = ["00:00", "00:30", "01:00", "01:30", "02:00", "02:30", "03:00", "03:30", "04:00", "04:30",
"05:00", "05:30", "06:00", "06:30", "07:00", "07:30", "08:00", "08:30", "09:00", "09:30",
"10:00", "10:30", "11:00", "11:30", "12:00", "12:30", "13:00", "13:30", "14:00", "14:30",
"15:00", "15:30", "16:00", "16:30", "17:00", "17:30", "18:00", "18:30", "19:00", "19:30",
"20:00", "20:30", "21:00", "21:30", "22:00", "22:30", "23:00", "23:30"];
var currentDate = moment().format('YYYY-MM-DD');
var currentTime = moment().format('HH:mm');

function setOptionsTimeList(selectName, endHourIndc) {
var checkMinute = currentTime.substring(3);
var checkHour = currentTime.substring(0,2);
var strHour = checkHour;
var strMinute = "00";

//현재 시간보다 30분 빠르게 시간을 설정.
if (checkMinute < 30) {
strMinute = "30";
} else {
strHour = Number(strHour) + 1;
if (strHour < 10) {
strHour = "0" + strHour;
}
}

//시작시간 보다 1시간 늦게 설정.
if (endHourIndc) {
strHour = Number(strHour) + 1;

if (strHour < 10) {
strHour = "0" + strHour;
}
}

//시간 선택 select 박스에서 트겆시간을 선택.
$.each(timeList, function(key, val) {
var str = "";
if (val == (strHour + ":" + strMinute)) {
str = "<option value=" + val + " selected='selected'>" + val + "</option>";
} else {
str = "<option value=" + val + ">" + val + "</option>";
}
$(selectName).append(str);
});
}

function saveSchedule() {
alert('saveSchedule Function');
dialog.dialog("close");
}

function setDatePicker(datepicker) {
$(datepicker).datepicker({
  dateFormat:'yy.mm.dd', //선택된 날짜 포맷(yyyy.mm.dd)
  monthNamesShort: ['1월','2월', '3월', '4월', '5월', '6월', '7월', '8월', '9월', '10월', '11월', '12월'],
  monthNames: ['1월','2월', '3월', '4월', '5월', '6월', '7월', '8월', '9월', '10월', '11월', '12월'],
  dayNamesMin: ['일', '월', '화', '수', '목', '금', '토'],  
  dayNamesShot: ['일', '월', '화', '수', '목', '금', '토'],
  dayNames: ['일요일', '월요일', '화요일', '수요일', '목요일', '금요일', '토요일'],
  firstDay: 1, //0: 일요일 부터 시작, 1:월요일 부터 시작
  autoSize: true, //default: false, input 사이즈를 자동으로 리사이즈.
  showAnim: "fold", //default: show
  showButtonPanel: true, //하단에 Today, Done 버튼 Display
  showWeek: true, //주차 보이기
  weekHeader: "주차", //default: Wk, 주차 헤드 부분의 명칭 설정
  changeMonth: true, //월 변경가능
  changeYear: true, //년 변경가능
  showMonthAfterYear: true, //년 뒤에 월 표시
  gotoCurrent: true //default: false, true일 경우에는 Today버튼 클릭 시 현재 일자로 이동하지 못함. false는 가능.
  });
}

//날짜와 시간 선택 부분을 초기화. 모두 선택 가능하도록...
function initialDateTime() {
$('#startDate').removeAttr('disabled');
    $('#endDate').removeAttr('disabled');
    $('#startTime').removeAttr('disabled');
    $('#endTime').removeAttr('disabled');
}

$(document).ready(function() {
var currentLangCode = 'ko';
var schedule = new Array();

// build the language selector's options
$.each($.fullCalendar.langs, function(langCode) {
$('#lang-selector').append(
$('<option/>')
.attr('value', langCode)
.prop('selected', langCode == currentLangCode)
.text(langCode)
);
});

// rerender the calendar when the selected option changes
$('#lang-selector').on('change', function() {
if (this.value) {
currentLangCode = this.value;
$('#calendar').fullCalendar('destroy');
renderCalendar();
}
});

dialog = $('#dialog-form').dialog({
autoOpen: false,
height: 400,
width: 450,
modal: true,
buttons: {
"Save": saveSchedule,
Cancel: function() {
dialog.dialog("close");
}
},
close: function() {
form[0].reset();
//allFields.removeClass("ui-state-error");
}
});

form = dialog.find( "form" ).on( "submit", function( event ) {
      event.preventDefault();
      saveSchedule();
    });
   
    //check box 클릭 이벤트  등록
    $('#allDay').click(function(){
    var chk = $(this).is(":checked");

    if (chk) {
    $('#startDate').attr('disabled', 'disabled');
    $('#endDate').attr('disabled', 'disabled');
    $('#startTime').attr('disabled', 'disabled');
    $('#endTime').attr('disabled', 'disabled');
    } else {
    $('#startDate').removeAttr('disabled');
    $('#endDate').removeAttr('disabled');
    $('#startTime').removeAttr('disabled');
    $('#endTime').removeAttr('disabled');
    }
    });
   
    setDatePicker('#startDate');
    setDatePicker('#endDate');
    setOptionsTimeList('#startTime', false);
    setOptionsTimeList('#endTime', true);
   
function renderCalendar() {
$('#calendar').fullCalendar({
header: {
//left: 'prevYear,prev,next,nextYear today',
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
defaultDate: currentDate,
lang: currentLangCode,
buttonIcons: false, // show the prev/next text
weekNumbers: true,
editable: true,
eventLimit: true, // allow 'more" link when too many events
dayClick: function(date, jsEvent, view) {
//alert('Clicked on: ' + date.format());
//alert('Coordinates: ' + jsEvent.pageX + ',' + jsEvent.pageY);
//alert('Current view: ' + view.name);
dialog.dialog("open");
initialDateTime();
}
});
}
   
renderCalendar();
});


</script>
<style>

body {
margin: 0;
padding: 0;
font-family: "Lucida Grande",Helvetica,Arial,Verdana,sans-serif;
font-size: 14px;
}

#top {
background: #eee;
border-bottom: 1px solid #ddd;
padding: 0 10px;
line-height: 40px;
font-size: 12px;
}

#calendar {
max-width: 900px;
margin: 40px auto;
padding: 0 10px;
}

</style>
</head>
<body>

<div id='top'>

Language:
<select id='lang-selector'> </select>

</div>
 
<div id="dialog-form" title="Create new schedule">
<form>
   <fieldset>
   <label for="title">Title</label>
   <input type="text" name="title" id="title" class="text ui-widget-content ui-corner-all">
   <label for="allDay">하루 종일</label>
   <input type="checkbox" id="allDay">
   <table>
    <tr>
    <td>  
    <label for="startDate">Start Date</label>
    </td>
    <td>
    <input type="text" name="startDate" id="startDate">
    </td>    
    <td>    
    <label for="startTime">Start Time</label>
    </td>
    <td>
<select id="startTime"></select>
</td>
</tr>
<tr>
<td>
   <label for="endDate">End Date</label>
</td>
<td>
   <input type="text" name="endDate" id="endDate">
</td>
<td>  
<label for="endDate">End Time</label>
</td>
<td>
<select id="endTime"></select>
</td>
</tr>
</table>
<label for="comments">Comments</label>
<textarea id="comments" name="comments"></textarea>
   <!-- Allow form submission with keyboard without duplicating the dialog button -->
   <input type="submit" tabindex="-1" style="position:absolute; top:-1000px">
   </fieldset>
  </form>
</div>

<div id='calendar'> </div>
</body>
</html>

2014년 8월 25일 월요일

jQuery의 datepicker를 이용해서 날짜를 선택할 수 있는 편리한 기능이다.
모양은 투박하지만 jQuery를 이용할 경우, 보다 편리하게 달력을 이용해서 일자를 선택할 수 있다.

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>jQuery UI Datepicker - Default functionality</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.11.1/themes/smoothness/jquery-ui.css" />
<style>
.ui-datepicker{ font-size: 12px; width: 200px; }
.ui-datepicker select.ui-datepicker-month{ width:30%; font-size: 11px; }
.ui-datepicker select.ui-datepicker-year{ width:40%; font-size: 11px; }
</style>
<script src="http://code.jquery.com/jquery-1.11.1.js"></script>
<script src="http://code.jquery.com/ui/1.11.1/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css" />
<script>
 $(function() {
  $("#datepicker").datepicker({
  dateFormat:'yy.mm.dd', //선택된 날짜 포맷(yyyy.mm.dd)
  monthNamesShort: ['1월','2월', '3월', '4월', '5월', '6월', '7월', '8월', '9월', '10월', '11월', '12월'],
  monthNames: ['1월','2월', '3월', '4월', '5월', '6월', '7월', '8월', '9월', '10월', '11월', '12월'],
  dayNamesMin: ['일', '월', '화', '수', '목', '금', '토'],  
  dayNamesShot: ['일', '월', '화', '수', '목', '금', '토'],
  dayNames: ['일요일', '월요일', '화요일', '수요일', '목요일', '금요일', '토요일'],
  firstDay: 1, //0: 일요일 부터 시작, 1:월요일 부터 시작
  autoSize: true, //default: false, input 사이즈를 자동으로 리사이즈.
  showAnim: "fold", //default: show
  showButtonPanel: true, //하단에 Today, Done 버튼 Display
  showWeek: false, //주차 보이기
  weekHeader: "주차", //default: Wk, 주차 헤드 부분의 명칭 설정
  changeMonth: true, //월 변경가능
  changeYear: true, //년 변경가능
  showMonthAfterYear: true, //년 뒤에 월 표시
  gotoCurrent: false //default: false, true일 경우에는 Today버튼 클릭 시 현재 일자로 이동하지 못함. false는 가능.
  });
 });

 function getDate() {
  alert($("#datepicker").datepicker("getDate"));
 }
</script>
</head>
<body>
 <p>
  Date: <input type="text" id="datepicker" /> <input type="button" id="btnDate" value="가져오기" onclick="getDate()" />
 </p>
</body>
</html>