'javascript'에 해당되는 글 10건

  1. 2009.05.21 Creating interactive alert, confirm, and prompt boxes using JavaScript
  2. 2009.05.20 javacript 로 만든 달력 샘플
  3. 2009.05.19 How to get value from TextBox, RadioButtonList, DropDownList, CheckBox through JavaScript
  4. 2009.04.17 javascript 에서 html 오브젝트 value 가져오기
  5. 2009.03.03 정규식을 이용한 숫자입력 체크 함수
  6. 2009.02.20 formatnumber
  7. 2009.02.20 Javascript 에서 알아야할 기초사항
  8. 2009.02.20 자바스크립트로 숫자에 "," 표시
  9. 2009.02.20 자바스크립트, 16진수 헥사(Hex), 2진수, 10진수 변환 함수; JavaScript
  10. 2009.02.06 Javascript Key Event Test Script
2009. 5. 21. 10:11

Creating interactive alert, confirm, and prompt boxes using JavaScript

출처 : Creating interactive alert, confirm, and prompt boxes using JavaScript

  The alert, confirm, and prompt boxes

The three "commands" involved in creating alert, confirm, and prompt boxes are:

  • window.alert()
  • window.confirm()
  • window.prompt()

Lets look at them in detail. The first one is:

window.alert()

This command pops up a message box displaying whatever you put in it. For example:

<body>
    <script type="text/javascript">
    window.alert("My name is George. Welcome!")
    </script>
</body>
        

As you can see, whatever you put inside the quotation marks, it will display it.

The second one is:

window.confirm()

Confirm is used to confirm a user about certain action, and decide between two choices depending on what the user chooses.

Click here for output: 

<script type="text/javascript">
    var x=window.confirm("Are you sure you are ok?")
    if (x)
    window.alert("Good!")
    else
    window.alert("Too bad")
</script>

There are several concepts that are new here, and I'll go over them. First of all, "var x=" is a variable declaration; it declares a variable ("x" in this case) that will store the result of the confirm box. All variables are created this way. x will get the result, namely, "true" or "false". Then we use a "if else" statement to give the script the ability to choose between two paths, depending on this result. If the result is true (the user clicked "ok"), "good" is alerted. If the result is false (the user clicked "cancel"), "Too bad" is alerted instead. (For all those interested, variable x is called a Boolean variable, since it can only contain either a value of "true" or "false").

The third one is:

window.prompt()

Prompt is used to allow a user to enter something, and do something with that info:

Click here for output: 

<script type="text/javascript">
    var y=window.prompt("please enter your name")
    window.alert(y)
</script>
            

The concept here is very similar. Store whatever the user typed in the prompt box using y. Then display it.

2009. 5. 20. 08:34

javacript 로 만든 달력 샘플

출처 : daum 지난 경기 보기에서 가져와서 조금 고침.

<html>
<head>
<title>
</title>
</head>
<style type="text/css">
a.topmenus {color:#031d6a;font-size:12px;font-weight:bold;text-decoration:none;}
a.topmenus:link{color:#031d6a;font-size:12px;font-weight:bold;text-decoration:none;}
a.topmenus:visited{color:#031d6a;font-size:12px;font-weight:bold;text-decoration:none}
a.topmenus:active{color:#031d6a;font-size:12px;font-weight:bold;text-decoration:underline}
a.topmenus:hover{color:#031d6a;font-size:12px;font-weight:bold;text-decoration:underline}

#gnb_layer_opacity {position:relative; float:left; background-color:#658cff; filter:alpha(opacity=30); -moz-opacity:0.3; display:none;}
:root .gnb_news_opacity {float:left; top:-72px; left:49px; width:69px; height:28px; z-index:1000;}
:root .gnb_sports_opacity {float:left; top:-72px; left:137px; width:73px; height:28px; z-index:1000;}
:root .gnb_tvnews_opacity {float:left; top:-72px; left:232px; width:113px; height:28px; z-index:1000;}
:root .gnb_sisa_opacity {float:left; top:-72px; left:362px; width:109px; height:28px; z-index:1000;}
:root .gnb_issue_opacity {float:left; top:-72px; left:496px; width:107px; height:28px; z-index:1000;}
:root .gnb_photo_opacity {float:left; top:-72px; left:624px; width:70px; height:28px; z-index:1000;}
:root .gnb_reporter_opacity {float:left; top:-72px; left:713px; width:107px; height:28px; z-index:1000;}
:root .gnb_weather_opacity {float:left; top:-72px; left:842px; width:69px; height:28px; z-index:1000;}
:root .gnb_menu_opacity {position:relative; float:left; margin:0; top:-20px; left:0; width:960px; height:18px; overflow:hidden; display:inline;}
* html .gnb_news_opacity {float:left; top:-76px; left:49px; width:69px; height:28px; z-index:1000;}
* html .gnb_sports_opacity {float:left; top:-76px; left:137px; width:73px; height:28px; z-index:1000;}
* html .gnb_tvnews_opacity {float:left; top:-76px; left:232px; width:113px; height:28px; z-index:1000;}
* html .gnb_sisa_opacity {float:left; top:-76px; left:362px; width:109px; height:28px; z-index:1000;}
* html .gnb_issue_opacity {float:left; top:-76px; left:496px; width:107px; height:28px; z-index:1000;}
* html .gnb_photo_opacity {float:left; top:-76px; left:624px; width:70px; height:28px; z-index:1000;}
* html .gnb_reporter_opacity {float:left; top:-76px; left:713px; width:107px; height:28px; z-index:1000;}
* html .gnb_weather_opacity {float:left; top:-76px; left:842px; width:69px; height:28px; z-index:1000;}
* html .gnb_menu_opacity {position:relative; float:left; margin:0; top:-24px; left:0; width:960px; height:18px; overflow:hidden;}
</style>
<!--달력 -->
<script language="JavaScript" type="text/JavaScript">
//오늘 날짜 설정
datToday = new Date();

//현재 년월일
NowThisYear = datToday.getFullYear();
NowThisMonth = datToday.getMonth()+1;
NowThisDay = datToday.getDate();


//날자를 선택하였을 경우
function doClick(sYear, sMonth, sDay)
{
var broad_dt = sYear + (sMonth<10?'0':'') + sMonth + (sDay<10?'0':'') + sDay;
document.location.href = '/exec/program/prog_main.php?prog_id=01&broad_dt='+broad_dt;
}

//2자리 숫자로 변경
function day2(sd)
{
var intd = new Number();
intd = parseInt(sd);

var str = new String();
if(intd < 10) {
str = "0" + intd;
} else {
str = "" + intd;
}
return str;
}

//년 정보를 콤보 박스로 표시
function getYearinfo(sYear, sMonth)
{
var intYear = new Number();
intYear = parseInt(sYear);

var min = 2000;
var max = (intYear > NowThisYear) ? intYear : NowThisYear;

var str = "<select onChange='ShowCalendar(this.value,"+sMonth+",1); return false;' style='width:70; background-color:#D4E6FD; color:#0958AD; font-weight:bold;'>";
for(var i=min; i<=max; i++) {
if (i == intYear) {
str += "<option value="+i+" selected>"+i+"년</option>";
} else {
str += "<option value="+i+">"+i+"년</option>";
}
}
str += "</select>";
return str;
}

//월 정보를 콤보 박스로 표시
function getMonthinfo(sYear, sMonth)
{
var intMonth = new Number();
intMonth = parseInt(sMonth);

var str = "<select onChange='ShowCalendar("+sYear+",this.value,1); return false;' style='width:55; background-color:#D4E6FD; color:#0958AD; font-weight:bold;'>";
for(var i=1; i<=12; i++) {
if (i == intMonth) {
str += "<option value="+i+" selected>"+i+"월</option>";
} else {
str += "<option value="+i+">"+i+"월</option>";
}
}
str += "</select>";
return str;
}

//달력 표현
function ShowCalendar(sThisYear, sThisMonth, sThisDay)
{
var Months_day = new Array(0,31,28,31,30,31,30,31,31,30,31,30,31)
var Weekday_name = new Array("일", "월", "화", "수", "목", "금", "토");

var intThisYear = new Number(), intThisMonth = new Number(), intThisDay = new Number();
intThisYear = parseInt(sThisYear);
intThisMonth = parseInt(sThisMonth);
intThisDay = parseInt(sThisDay);
//값이 없을 경우
if(intThisYear == 0) intThisYear = datToday.getFullYear();
if(intThisMonth == 0) intThisMonth = datToday.getMonth()+1; // 월 값은 실제값 보다 -1 한 값임.
if(intThisDay == 0) intThisDay = datToday.getDate();
//윤년 처리
if((intThisYear % 4)==0) {
if((intThisYear % 100) == 0) {
if((intThisYear % 400) == 0) {
Months_day[2] = 29;
}
} else {
Months_day[2] = 29;
}
}

//이전.후 년월 설정 (화살표 이동)
switch(intThisMonth) {
case 1:
intPrevYear = intThisYear -1;
intPrevMonth = 12;
intNextYear = intThisYear;
intNextMonth = 2;
break;
case 12:
intPrevYear = intThisYear;
intPrevMonth = 11;
intNextYear = intThisYear + 1;
intNextMonth = 1;
break;
default:
intPrevYear = intThisYear;
intPrevMonth = intThisMonth - 1;
intNextYear = intThisYear;
intNextMonth = intThisMonth + 1;
break;
}

//호출날짜 객체 생성
datThisDay = new Date(intThisYear, intThisMonth, intThisDay);
//호출날짜의 요일
intThisWeekday = datThisDay.getDay();
//호출날짜의 요일명
varThisWeekday = Weekday_name[intThisWeekday];
//호출날짜의 마지막일자
intLastDay = Months_day[intThisMonth];

//호출날짜의 월의 1일로 날짜 객체 생성(월은 0부터 11까지의 정수(1월부터 12월))
datFirstDay = new Date(intThisYear, intThisMonth-1, 1);
//호출날짜의 달 1일의 요일을 구함 (0:일요일, 1:월요일)
intFirstWeekday = datFirstDay.getDay();
//노출 처리용
intThirdWeekday = intFirstWeekday; //요일
thirdPrintDay = 1; //일

Stop_flag = 0;
Cal_HTML = "<table border='0' cellspacing='0' cellpadding='0' style='margin-top:2'>";
Cal_HTML += "<tr>";
Cal_HTML += "<td><img onClick='ShowCalendar("+intPrevYear+","+intPrevMonth+",1);' alt='"+intPrevYear+"-"+intPrevMonth+"' src='http://newsimg.kbs.co.kr/images/200602/common/b_back.gif' align=absmiddle></td>";
Cal_HTML += "<td style='color:#8D6A0A; padding-left:8'>"+getYearinfo(intThisYear,intThisMonth)+"</td>";
Cal_HTML += "<td style='color:#8D6A0A; padding-left:8'>"+getMonthinfo(intThisYear,intThisMonth)+"</td>";
Cal_HTML += "<td style='padding-left:8'><img onClick='ShowCalendar("+intNextYear+","+intNextMonth+",1);' alt='"+intNextYear+"-"+intNextMonth+"' src='http://newsimg.kbs.co.kr/images/200602/common/b_front.gif' align=absmiddle></td>";
Cal_HTML += "</tr>";
Cal_HTML += "</table>\n";

Cal_HTML += "<table border='0' cellspacing='0' cellpadding='0' style='margin-top:2;'>";
Cal_HTML += "<tr height=24 align=center>";
Cal_HTML += "<td width=27 style='color:red;'>일</td>";
Cal_HTML += "<td width=27 style='color:green;'>월</td>";
Cal_HTML += "<td width=27 style='color:green;'>화</td>";
Cal_HTML += "<td width=27 style='color:green;'>수</td>";
Cal_HTML += "<td width=27 style='color:green;'>목</td>";
Cal_HTML += "<td width=27 style='color:green;'>금</td>";
Cal_HTML += "<td width=27 style='color:blue;'>토</td>";
Cal_HTML += "</tr>\n";

for(intLoopWeek=1; intLoopWeek<7; intLoopWeek++)  { // 주단위 루프 시작, 최대 6주
if(Stop_flag==1) { break; }
Cal_HTML += "<tr height=20 align=center>"
for(intLoopDay=1; intLoopDay<=7; intLoopDay++)  { // 요일단위 루프 시작, 일요일 부터
//월의 first day의 요일 위치
if(intThirdWeekday > 0)  {
Cal_HTML += "<td width=27></td>";
intThirdWeekday--;
continue;

//월의 last day의 요일 위치
if(thirdPrintDay > intLastDay)  {
Cal_HTML += "<td width=27></td>";
continue;

Cal_HTML += "<td width=27 title='"+intThisYear+"-"+day2(intThisMonth).toString()+"-"+day2(thirdPrintDay).toString()+"'";

Cal_HTML += "><a href='javascript:doClick("+intThisYear+","+intThisMonth+","+thirdPrintDay+");'"
switch(intLoopDay) {
case 1: // 일요일
Cal_HTML += " style='color:red;'"
break;
case 7: // 토요일
Cal_HTML += " style='color:blue;'"
break;
default: // 평일
Cal_HTML += " style='color:black;'"
break;
}
//오늘인가?
if(intThisYear == NowThisYear && intThisMonth==NowThisMonth && thirdPrintDay==NowThisDay)  {
Cal_HTML += "><b>"+thirdPrintDay+"</b></a>";
} else {
Cal_HTML += ">"+thirdPrintDay+"</a>";
}

thirdPrintDay++;
Cal_HTML += "</td>";

// 만약 날짜 값이 월말 값보다 크면 루프문 탈출
if(thirdPrintDay > intLastDay)  {
Stop_flag = 1;
}
}

Cal_HTML += "</tr>\n";
}

Cal_HTML += "</table>\n";

document.all.minical.innerHTML = "";
document.all.minical.innerHTML = Cal_HTML;

//for debug
//document.all.source.value = Cal_HTML;
}
</script>

</body>
<body>
<table width="215" border="0" cellspacing="0" cellpadding="0" style="border:1px solid #9FC8FD">
<tr><td style="padding:0 5 4 3; border:1px solid #E0ECFC; background-color:#D4E6FD"><center>달 력</center>
<table width="100%" border="0" cellpadding="0" cellspacing="0" style="border:1px solid #659BE0">
<tr><td align="center" valign="top" style="padding:7 12 7 12; background-color:#FFFFFF">
<div id="minical"></div>
</td></tr>
</table>
</td></tr>
</table>

<script language="JavaScript" type="text/JavaScript">ShowCalendar(2009,5,15);</script>

<!--/달력 -->
<table width="100%" border="0" cellpadding="0" cellspacing="0"><tr><td height="10"></td></tr></table>
</body>
</html>
2009. 5. 19. 10:22

How to get value from TextBox, RadioButtonList, DropDownList, CheckBox through JavaScript

출처 : http://www.dotnetfunda.com/articles/article72.aspx

내가 만든 샘플 코드 링크 : 

신규 Web Form 에 스크립트와 html만 복사하면 됨.

In day to day life generally we need to get values from asp.net server controls through JavaScript while developing web applications. I found several questions on the internet for the same subject. In this article I am going to show how to get values from asp.net controls like TextBox, RadioButtonList, DropDownList, CheckBoxes. 


This picture is the UI screenshots of the the code I am going to present in this article



Getting TextBox Value in JavaScript

.aspx page code
Following code will render a TextBox and a Button control as displayed in the picture above.

<table> <tr> <th colspan="2" align="left"> Getting TextBox Value in JavaScript: </th> </tr> <tr> <td> <asp:TextBox ID="txt1" runat="server"></asp:TextBox> </td> <td> <input type="button" value="Submit" onclick="GetTextBoxValue('<%= txt1.ClientID %>')" /> </td> </tr> </table>


JavaScript function
Following code is JavaScript function to get value from TextBox control.
// Get TextBox value
function GetTextBoxValue(id)
{
    alert(document.getElementById(id).value);
}


Getting DropDownList/ListBox selected value

Following code will render a DropDown (Html select control) and a button as displayed in the picture above.
.aspx code
<table>
<tr>
    <th colspan="2" align="left">
        Getting DropDown/ListView Value
    </th>
</tr>
<tr>
    <td>
        <asp:DropDownList ID="dropDown" runat="Server">
            <asp:ListItem Text="Item 1" Value="1" Selected="True"></asp:ListItem>
            <asp:ListItem Text="Item 2" Value="2"></asp:ListItem>
            <asp:ListItem Text="Item 3" Value="3"></asp:ListItem>
        </asp:DropDownList>
    </td>
    <td>
        <input type="button" value="Submit" onclick="GetDropDownValue('<%= dropDown.ClientID %>')" />
    </td>
</tr>
</table>

JavaScript Code
Following is the JavaScript function to get the value from DropDown control
// Get DropDown value
function GetDropDownValue(id)
{
    alert(document.getElementById(id).value);
}


Getting RadioButtonList selected value

Following code will render RadioButtons and a button as displayed in the picture above.
.aspx code
<table>
    <tr>
        <th colspan="2" align="left">
            Getting RadioButton Value
        </th>
    </tr>
    <tr>
        <td>
            <asp:RadioButtonList ID="radiobuttonlist1" runat="Server" RepeatLayout="flow" RepeatDirection="horizontal">
                <asp:ListItem Text="Radio 1" Value="1" Selected="True"></asp:ListItem>
                <asp:ListItem Text="Radio 2" Value="2"></asp:ListItem>
                <asp:ListItem Text="Radio 3" Value="3"></asp:ListItem>
            </asp:RadioButtonList>
        </td>
        <td>
            <input type="button" value="Submit" onclick="GetRadioButtonValue('<%= radiobuttonlist1.ClientID %>')" />
        </td>
    </tr>
</table>

JavaScript Code
Following is the JavaScript function to get the selected value from RadioButtons
// Get radio button list value
function GetRadioButtonValue(id)
{
    var radio = document.getElementsByName(id);
    for (var ii = 0; ii < radio.length; ii++)
    {
        if (radio[ii].checked)
            alert(radio[ii].value);
    }
}


Getting CheckBox checked status

Following code will render a checkbox and a button as displayed in the picture above.
.aspx code
<table>
    <tr>
        <th colspan="2" align="left">
            Getting Checkbox Value
        </th>
    </tr>
    <tr>
        <td>
            <asp:CheckBox runat="server" ID="checkBox1" Text="Check Box" />
        </td>
        <td>
            <input type="button" value="Submit" onclick="GetCheckBoxValue('<%= checkBox1.ClientID %>')" />
        </td>
    </tr>
</table>

JavaScript Code
Following is the JavaScript function to get value from a Checkbox.
// Get Checkbox checked status
function GetCheckBoxValue(id)
{
    alert(document.getElementById(id).checked);
}



Show/Hide Text using

Following code will render three buttons and a table element having some text as displayed in the picture above.
.aspx code

<b>Show/Hide display text</b><br />
<input type="button" value="Toggle Display Following Text" onclick="ToggleFollowingText('table1')" />
<input type="button" value="Show Only" onclick="ShowOrHide('show', 'table1')" /> 
<input type="button" value="Hide Only" onclick="ShowOrHide('hide', 'table1')" />
<table id="table1">
    <tr>
        <td style="background-color:Aqua">
            This is my hidden text, You can play with it by clicking above button.
        </td>
    </tr>
</table>


JavaScript Code
Following is the JavaScript function to toggle display the table and show and hide element the table.

// Show/Hide element function ToggleFollowingText(id) { document.getElementById(id).style.display == '' ? document.getElementById(id).style.display = 'none' : document.getElementById(id).style.display = ''; } // Either show or hide element function ShowOrHide(condition, id) { if (condition == 'show') document.getElementById(id).style.display = ''; else if (condition == 'hide') document.getElementById(id).style.display = 'none'; }
2009. 4. 17. 17:30

javascript 에서 html 오브젝트 value 가져오기


javascript 에서 html 오브젝트 value 가져오기

1과 2는 동일하게 동작한다.

1. ---------------------------------------------
        var strWhNm = "<%=txtWhNm.ClientID%>";
        var strWhCd = "<%=hfWhCd.ClientID%>";
        var strProdClassNm = "<%=txtProdClassNm.ClientID %>";
        var strProdClassCd = "<%=hfProdClassCd.ClientID%>";
        var strProdNm = "<%=txtProdNm.ClientID %>";
        var strProdCd = "<%=hfProdCd.ClientID%>";

        var strWhNmValue = document.all[strWhNm].value;
        var strWhCdValue = document.all[strWhCd].value;
        var strProdClassNmValue = document.all[strProdClassNm].value;
        var strProdClassCdValue = document.all[strProdClassCd].value;
        var strProdNmValue = document.all[strProdNm].value;
        var strProdCdValue = document.all[strProdCd].value;

2. ---------------------------------------------
        var strWhNmValue = window.document.forms[0].<%=txtWhNm.ClientID%>.value;
        var strWhCdValue = window.document.forms[0].<%=hfWhCd.ClientID%>.value;
        var strProdClassNmValue = window.document.forms[0].<%=txtProdClassNm.ClientID%>.value;
        var strProdClassCdValue = window.document.forms[0].<%=hfProdClassCd.ClientID%>.value;
        var strProdNmValue = window.document.forms[0].<%=txtProdNm.ClientID%>.value;
        var strProdCdValue = window.document.forms[0].<%=hfProdCd.ClientID%>.value;

2009. 3. 3. 10:41

정규식을 이용한 숫자입력 체크 함수

내가 만든 숫자입력 체크 정규식
if (!Regex.IsMatch(txtInput.Text, @"^[0-9\.]*$"))
{
    // 숫자 아님
    txtInput.Text = string.Empty;
    txtInput.Select();                                                    
    return;
}
else
{
    // 숫자임
    fnCall();
}


* 단점 : 한글인 경우 체크가 안됩니다....ㅠㅠ

 

// 숫자, 콤마(,), 소숫점(.) 허용한 숫자체크

// 반환값 true / false

function IsNumber(strNumber)
{
    var reg = RegExp(/^(\d|-)?(\d|,)*\.?\d*$/);
    return reg .test(strNumber);
}


// IsNumber함수를 이용한 필드 입력값 체크

// 사용방법 : <input type="text" onkeyup="CheckNumber(this)">

function CheckNumber(field) {
   if( !IsNumber(field.value) )
   {
      alert!("숫자형식만 입력해주십시오.");
      field.value="0";
      field.focus();
      field.select();
   }
}

 

출처 : 몽키님 블로그

 (http://blog.daum.net/monkeychoi/4967162?srchid=BR1http%3A%2F%2Fblog.daum.net%2Fmonkeychoi%F4967162)

2009. 2. 20. 10:49

formatnumber

별자리님께서 올려주신 formatnumber에 대한 이야기입니다.^^;
두고두고 도움이 될듯 싶어... 또 미쳐 양해도 구하지 않고 걍,, 올립니다. -_-;
formatnumber함수에 대해 자알 정리를 해주셨으니 참고들 하시구요^^
http://www.tubemusic.com
운영하시는 사이트에도 한번 놀러들 가보시구요^^;
=================================================================================
FormatNumber함수를 사용하세요!!
 
일반적으로.. 소수점 및 3자리마다 콤마(,) 사용시에 많이 사용됩니다..
 
) 12345 -> 12,345 이렇게 표현할려면
     DATA = 12345
     FormatNumber(DATA, 0)
     이렇게 처리하면..됩니다...
 
참고로.. 위의 DATA NULL(값이 존재하지 않는다)이면.. 오류가 발생하므로
꼭 주의 하시길 바랍니다..
 
 
  FormatNumber 함수란? 
 
숫자로 형식화된 식을 반환합니다. 
 
FormatNumber(Expression [,NumDigitsAfterDecimal [,IncludeLeadingDigit 
[,UseParensForNegativeNumbers [,GroupDigits]]]])
 
인수
Expression
 
필수적인 요소. 형식이 지정되는 식입니다.
 
NumDigitsAfterDecimal
 
선택적인 요소. 표시될 소수점 이하의 자릿수를 나타내는 숫자 값입니다. 기본값인 -1은 컴퓨터의 국가별 
설정을 사용함을 나타냅니다.
 
IncludeLeadingDigit
 
선택적인 요소. 소수점 이하의 유효 숫자 앞에 0을 표시할지 여부를 나타내는 Tristate 상수입니다. 그 값
에 대해서는 아래의 설정을 참조하십시오.
 
UseParensForNegativeNumbers
 
선택적인 요소. 음수 값을 괄호 안에 넣을지 여부를 나타내는 Tristate 상수입니다. 그 값에 대해서는 아래
의 설정을 참조하십시오. 
 
GroupDigits
 
선택적인 요소. 제어판에 설정된 그룹 구분 기호를 사용하여 숫자를 구분할지 여부를 나타내는 Tristate 
수입니다. 그 값에 대해서는 아래의 설정을 참조하십시오. 
 
설정
IncludeLeadingDigit, UseParensForNegativeNumbers, GroupDigits 인수는 아래 설정을 가집니다.
 
상수                     값 설명 
TristateTrue          -1 True 
TristateFalse          0 False 
TristateUseDefault -2 컴퓨터의 국가별 설정 값을 사용합니다. 
 
 
참고
하나 이상의 선택적인 인수를 생략하면 컴퓨터의 국가별 설정 값을 생략된 인수 값으로 사용합니다. 
 
메모   모든 설정 정보는 국가별 설정의 숫자 탭에 있습니다.
 
 
 
 
예제)  1234.123
   FormatNumber(DATA, 4)   -> 1,234.1230
   FormatNumber(DATA, 3)   -> 1,234.123
   FormatNumber(DATA, 2)   -> 1,234.12
   FormatNumber(DATA, 1)   -> 1,234.1
   FormatNumber(DATA, 0)   -> 1,234

 

MIME-Version: 1.0 Content-Location: file:///C:/9EC32DB0/file1344.htm Content-Transfer-Encoding: quoted-printable Content-Type: text/html; charset=s-ascii"
별자리님께서 올려주신 formatnumber에 대한 이야기입니다.^^;
두고두고 도움이 될듯 싶어... 또 미쳐 양해도 구하지 않고 걍,, 올립니다. -_-;
formatnumber함수에 대해 자알 정리를 해주셨으니 참고들 하시구요^^
http://www.tubemusic.com
운영하시는 사이트에도 한번 놀러들 가보시구요^^;
=================================================================================
FormatNumber함수를 사용하세요!!
 
일반적으로.. 소수점 및 3자리마다 콤마(,) 사용시에 많이 사용됩니다..
 
) 12345 -> 12,345 이렇게 표현할려면
     DATA = 12345
     FormatNumber(DATA, 0)
     이렇게 처리하면..됩니다...
 
참고로.. 위의 DATA NULL(값이 존재하지 않는다)이면.. 오류가 발생하므로
꼭 주의 하시길 바랍니다..
 
 
  FormatNumber 함수란? 
 
숫자로 형식화된 식을 반환합니다. 
 
FormatNumber(Expression [,NumDigitsAfterDecimal [,IncludeLeadingDigit 
[,UseParensForNegativeNumbers [,GroupDigits]]]])
 
인수
Expression
 
필수적인 요소. 형식이 지정되는 식입니다.
 
NumDigitsAfterDecimal
 
선택적인 요소. 표시될 소수점 이하의 자릿수를 나타내는 숫자 값입니다. 기본값인 -1은 컴퓨터의 국가별 
설정을 사용함을 나타냅니다.
 
IncludeLeadingDigit
 
선택적인 요소. 소수점 이하의 유효 숫자 앞에 0을 표시할지 여부를 나타내는 Tristate 상수입니다. 그 값
에 대해서는 아래의 설정을 참조하십시오.
 
UseParensForNegativeNumbers
 
선택적인 요소. 음수 값을 괄호 안에 넣을지 여부를 나타내는 Tristate 상수입니다. 그 값에 대해서는 아래
의 설정을 참조하십시오. 
 
GroupDigits
 
선택적인 요소. 제어판에 설정된 그룹 구분 기호를 사용하여 숫자를 구분할지 여부를 나타내는 Tristate 
수입니다. 그 값에 대해서는 아래의 설정을 참조하십시오. 
 
설정
IncludeLeadingDigit, UseParensForNegativeNumbers, GroupDigits 인수는 아래 설정을 가집니다.
 
상수                     값 설명 
TristateTrue          -1 True 
TristateFalse          0 False 
TristateUseDefault -2 컴퓨터의 국가별 설정 값을 사용합니다. 
 
 
참고
하나 이상의 선택적인 인수를 생략하면 컴퓨터의 국가별 설정 값을 생략된 인수 값으로 사용합니다. 
 
메모   모든 설정 정보는 국가별 설정의 숫자 탭에 있습니다.
 
 
 
 
예제)  1234.123
   FormatNumber(DATA, 4)   -> 1,234.1230
   FormatNumber(DATA, 3)   -> 1,234.123
   FormatNumber(DATA, 2)   -> 1,234.12
   FormatNumber(DATA, 1)   -> 1,234.1
   FormatNumber(DATA, 0)   -> 1,234
2009. 2. 20. 10:47

Javascript 에서 알아야할 기초사항

출처 : http://mainia.tistory.com/269?srchid=BR1http%3A%2F%2Fmainia.tistory.com%2F269

DOM 객체의 기본 구조도를 알아야한다. 이객체들이 어디에 속해있는지 표를 보고 알아야할것이다


1.
내장함수

(1) 내장메시지 함수

alert("Hello."); confirm("정말로 삭제할껴?"); prompt(메시지, 초기값);

 

(2) 일반내장 함수

isFinite(number) : number한수이면 true, 아니면 false를 리턴

isNaN(value) : value가 순수한 문자이면 true, 숫자형태의 문자이면 false를 리턴

number(obj) : obj를 숫자로 변환하여 리턴

string(obj) : obj를 문자로 변환하여 리턴

eval(수식문자열 또는 Object 문자열) : 수식을 처리한 결과를 리턴, Object로 변환하여 리턴

parseInt(문자열, [진수]) : 문자열을 정수로 변환하여 리턴

parseFloat(문자열) : 문자열을 float-실수형으로 변환하여 리턴

escape(string) : ASCII 스트링을 URL로 인코딩

unescape(string) : ASCII 스트링을 URL로 디코딩

encodeURI(string) : 주어진 문자열을 URI encoding 한다.

decodeURI(string) : 주어진 문자열에서 encoding URI decoding 한다.

encodeURIComponent(string) : 주어진 문자열을 URI encoding 한다.

decodeURIComponent(string) :  주어진 문자열에서 encoding URI decoding 한다.

 

(3) 문자인코딩 함수

encodeURI() / decodeURI() : 다음문자만 인초딩한다  è  ; / ? : @ & = + $ , - _ . ! ~ * ' ( ) #

encodeURIComponent() / decodeURIComponent() :

알파벳과 숫자 Alphanumeric Characters 외의, 대부분의 문자를 모두 인코딩한다.

escape() / unescape() : encodeURI() encodeURIComponent() 의 중간 정도의 범위로 문자 인코딩

 

2. 내장 객체

(1) Object 객체

var book = new Object(); // empty Object --> var book = {};

book.title = "내장객체";

book.author = "kspark";

book.published_date = new Array('2006', '2007');

book.getInformation = function() { return this.title + ", " + this.author; }

 

function DisplayPropertyNames(obj){

             var names = "";

             for( var name in obj ) names += name + "\n";

             alert(names);

             alert(obj.getInformation());

}.

 

(2) Function 객체 : 함수 객체, 객체변수 = new Function([매개변수 리스트], 함수의 처리 내용)

var square = function(x) { return x*x }

var sports = new Object();

sports.soccer = new Function('var name = "soccer"; return name;');

var sum = new Function( "x", "y", "return x+y" );

function execute(){

   alert( "Sports name : " + sports.soccer() );

   alert( "sum : " + sum(5,10) );

}

 

(3) Array 배열 객체

length 속성, join(문자열),reverse(),sort(compareFunction),slice(시작위치,종료위치),concat(배열객체)

var list = new Array();

 

(4) Date 날짜 객체

var date = new Date();

 

getDate, getDay, getFullYear, getHours, getMilliseconds, getMinutes, getMonth,

getSeconds, getTime,  getTimezoneOffset, getUTCDate, getUTCDay,

getUTCFullYear, getUTCHours, getUTCMilliseconds, getUTCMinutes,

getUTCMonth, getUTCSeconds, getYear, parse, setDate, setFullYear, setHours,

setMilliseconds, setMinutes, setMonth, setSeconds, setTime, setUTCDate,

setUTCHours, setUTCMilliseconds, setUTCMinutes,  setUTCMonth, setUTCSeconds,

setYear, goGMTString, toLocaleString, toString, toUTCString, UTC, valueOf

 

(5) String 객체

문자열 조작 메소드

toLowerCase(), toUpperCase(), charAt(인덱스), substring(인덱스1, 인덱스2), slice(인덱스1, 인덱스2),

substr(시작인덱스, 길이), indexOf(문자열), lastIndexOf(문자열), concat(문자열), split(분리자, [개수]), charCodeAt([인덱스]), fromCharCode(숫자)

 

글자 모양을 변경하는 메소드

big(), small(), blink(), bold(), fixed(), italics(), strike(가운데줄), sub(아래첨자),sup(위첨자),

fontcolor(""), fontsize(크기)

 

위치 이동하는 메소드

anchor("책갈피명"), link("이동위치");

 

var str = "Hello! David";

str.slice(6, str.length);   str.link(#david);

 

(6) 수학관련 객체 Math : 각종 수학적 계산을 돕는 Math 객체

Math.PI, Math.sin(x), Math.abs(x), Math.max(x,y)

 

(7) 수치관련 객체 Number

수치 형태의 문자열을 수치 데이터로 변환하는 객체, new Number(수치 형태의 문자열);

var Ten = new Number("10");

 

(8) 논리형 객체 Blooean : 논리 객체, new Boolean(논리값);

 

(9) 스크린 화면 객체 Screen : Screen.availWidth, availHeight(화면의 실제 너비, 높이 ),

Screen.width, height(스크린 실제 너비, 높이), pixelDepth(익스플로워 지원안됨),

colorDepth(사용가능색상수)

 

(10) Event : 이벤트 객체

이벤트 함수의 종류

Abort (onAbort) : 문서를 읽다가 중단시켰을때(브라우저에서 멈춤을 눌렀을때)

Blur (onBlur) : 사용자가 입력을 포커스를 원도우나 입력양식 요소에서 제거했을때

Click (onClick) : 사용자가 입력 양식의 요소나 링크를 클릭 했을때

Change (onChange) : 사용자가 요소의 값을 바꾸었을 때

DblClick (onDblclk) : 사용자가 입력 양식의 요소나 링크를 더블 클릭 했을때

DragDrop (onDragDrop) : 마우스를 드래그 하는 순간 발생

Error (onError) : 문서나 이미지를 읽는 중에 강제로 중지하는 순간 발생

Focus (onFocus) : 사용자가 입력 포커스를 원도우나 입력 양식의 요소로 이동했을 때

KeyDown (onKeyDown) : 사용자가 키를 눌렀을때

KeyPress (onKeyPress) : 사용자가 키를 누르고 있을때

KeyUp( onKeyUp) : 사용자가 눌렀던 키를 놓았을때

Load(onLoad) : 브라우저에서 문서을 읽었을때

MouseDown(onMouseDown) : 마우스를 누르는 순간 발생함

MouseMove(onMouseMove) : 마우스가 움직일 때

MouseOver(onMouseOver) : 사용자가 link anchor위로 마우스로 옮겼을때

MouseOut(onMouseOut) : 마우스가 특정 영역 안에 있다가 나갔을때

MouseUp(onMouseUp) : 마우스 커서를 이미지 맵이나 링크 위에서 내려 놓을 때

Move(onMove) : 윈도우나 프레임의 위치가 이동되는 순간 발생

Reset (onReset) : 사용자가 입력 양식을 초기화 했을 때

 

이벤트에서 발생하는 객체들의 종류이며 , 네스케이프와 익스플로어의 경우를 따로 분리했다.

[네스케이프  에서의 이벤트 객체]

data : DragDrop 이벤트로 인해 드롭된 객체의 URL이 들어있는 스트링 배열

height, width : 윈도우나 프레인의 길이와 너비(픽셀표시)

pageX, pageY : 픽셀로 나타낸 커서의 수평/수직 위치(페이지에서의 상대적위치)

screenX, screenY : 픽셀로 나타낸 커서의 수평/수직 위치(화면에서의 상대적 위치)

layerX, layerY : 픽셀로 나타낸 커서의 수평/수직 위치, 이벤트가 발생한 레이어에 대한 상대적 위치.

target : 이벤트가 전송된 원래 객체

type : 발생한 이벤트 유형

which : 눌려진 마우스 버튼(left:1, middle:2, right:3)이나 눌려진 키의 ASCII

modifiers : 마우스나 키 이벤트와 연관된 수정자 키

(ALT_MASK,CONTROL_MASK,SHIFT_MASK,META_MASK) 를 식별

 

[익스플로어 에서의 이벤트 객체]

screenX, screenY : 픽셀로 나타낸 커서의 수평/수직 위치(화면에서의 상대적 위치)

clientX, clientY : 픽셀로 나타낸 커서의 수평/수직 위치, 이벤트가 발생한 웹페이지에서의 상대적 위치

offsetX, offsetY : 픽셀로 나타낸 커서의 수평/수직 위치,이벤트가 발생한 컨테이너에 대한 상대적 위치

X, Y : 픽셀로 나타낸 커서의 수평/수직 위치, 이벤트가 발생한 문서에 대한 상대적 위치

srcElement : 이벤트가 전송된 원래 객체

type : 발생한 이벤트 유형

keyCode : 키 누름과 연관된 Unicode 키 코드를 식별

button : 이벤트가 발생했을 때 눌려진 마우스 버튼 식별(0:눌려진버튼없음, 1:, 2:, 4:)

altkey,ctrlkey,shiftkey : true false로 설정하여 이벤트가 발생했을 때 Alt키와 Control, Shift 키 중에 어떤 것이 눌려졌는지 알려준다.

cancelBubble : true false로 설정하여 이벤트 버블링을 취소하거나 활성화한다.

fromElement, toElement : 이동 중인 HTML 요소 지정

reason : 데이터 소스 객체에 대한 데이터 전송 상태를 나타내는데 사용

returnValue : true false로 설정하여 이벤트 핸들러의 리턴값을 나타낸다. 이벤트 핸들러에서 true false를 리턴하는 것과 같다.

 

위에서 열거한 이런 내용을 암기는 하지 못하더라도 모두 이해하고 어떤경우에 쓰이는지를

파악하고 있어야하겠다. 자바스크립트를 사용하는 사람들의 가장 기본적으로 갖추어야 하는 지식이다.



2009. 2. 20. 10:44

자바스크립트로 숫자에 "," 표시

자바스크립트로 숫자 세자리 단위마다 "," 를 찍어준다.
소수점은 ","를 찍지 않는다.

function formatNumber(num) {
        var str = String(num).split(".");
        
        var re = /(-?[0-9]+)([0-9]{3})/;
        while (re.test(str[0])) {
            str[0] = str[0].replace(re, "$1,$2");
        }
        if (str.length == 2)
            return str[0] + "." + str[1];
        else
            return str[0];
    }
2009. 2. 20. 09:51

자바스크립트, 16진수 헥사(Hex), 2진수, 10진수 변환 함수; JavaScript

출처 : http://mwultong.blogspot.com/2007/04/16-hex-2-10-javascript.html


자바스크립트에서, 10진수 숫자를 16진수나 2진수로 상호 변환하는 방법입니다.

"toString(진법)" 이라는 메서드 속에 진법을 넣어주면 됩니다. 가령, 16진수로 변환하려면 16을 넣으면 됩니다.

JavaScript 진법 변환: 십진수 십육진수 이진수


예제 소스 파일명: example.html
<script type="text/javascript">

var n;


// 10진수 255를 16진수로 변환
n = (255).toString(16);
document.write(n, '<br />');
// 출력 결과: ff


// 10진수 255를 2진수로 변환
n = (255).toString(2);
document.write(n, '<br />');
// 출력 결과: 11111111


// 16진수 ff를 10진수로 변환
n = (0xff).toString(10);
document.write(n, '<br />');
// 출력 결과: 255


// 16진수 0a를 2진수로 변환
n = (0x0a).toString(2);
document.write(n, '<br />');
// 출력 결과: 1010


// 변수 속의 10진수 123을 16진수로 변환
var foo = 123;
n = foo.toString(16);
document.write(n, '<br />');
// 출력 결과: 7b


// 변수 속의 10진수 123을 16진수로 변환
// + 대문자로 변환
var foo = 123;
n = foo.toString(16).toUpperCase();
document.write(n, '<br />');
// 출력 결과: 7B


</script>



11111111 이런 숫자는 2진수인지 10진수인지 알 수 없으므로, 우선 이 숫자를 문자열로 저장한 후, parseInt()에서 2진수로 간주하여 10진수로 변환하고, 그것을 다시 다른 진법, 예를 들어 16진수로 변환하면 됩니다. 다음 예제와 같습니다.

<script type="text/javascript">

var n = '11111111'; // 2진수를 문자열로서 저장

n = parseInt(n, 2); // n 속의 숫자를 2진수로 취급하여, 10진수 숫자로 변환


// 10진수화된 2진수를, 16진수로 변환
n = n.toString(16);
document.write(n, '<br />');
// 출력 결과: ff

</script>
2009. 2. 6. 11:40

Javascript Key Event Test Script

링크 : http://unixpapa.com/js/testkey.html

링크 : http://unixpapa.com/js/key.html

자바스크립트 키 이벤트 발생 내역 체크 테스트 사이트
자바스크립트 키 이벤트 내역 및 KeyCode를 확인할 수 있는 사이트,
바코드 스캐너 등을 통하여 키 이벤트 발생 내역을 체크할 때 유용하다.