사용자 도구

사이트 도구


wiki:javascript:jquery

jQuery

  • description : jQuery 관련 내용 기술
  • author : 주레피
  • email : dhan@repia.com
  • lastupdate : 2020-03-18

속성 변경

Ajax

Autocomplete

Case Study

Button

값 가져오기

<!doctype html>
<html lang="ko">
    <head>
        <meta charset="utf-8">
        <title>button Test</title>
        <script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
        <script>
            $( document ).ready( function() {
                $("#button").click(function(){
                    alert($(this).attr('value'));
                });
            });
        </script>
    </head>
    <body>
        <button id="button" value="huskdoll"> 클릭 </button>
    </body>
</html>
값 입력은 $(this).attr('value', ${value}); 형식으로 진행

jQuery 버튼값 가져오기

Click

How to remove “onclick” with JQuery

// Old Way(pre-1.7)
$(selector).attr("onclick", "").unbind("click");
// New Way(1.7+)
$(selector).prop("onclick", null).off("click");

Official docs .click()

Closest(), parents()

DatePicker

DatePicker란 jQuery에서 제공하는 widget중 하나로, 날짜를 다룰 때 UI 형식으로 쉽게 날짜를 선택 하도록 도와주는 역할을 하는 widget이다

(DatePicker를 사용하기 위해서는 기본적으로 다음의 3가지 File을 import해야 한다)

// jQuery UI CSS파일 
<link rel="stylesheet" href="http://code.jquery.com/ui/1.8.18/themes/base/jquery-ui.css" type="text/css" />  
// jQuery 기본 js파일
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>  
// jQuery UI 라이브러리 js파일
<script src="http://code.jquery.com/ui/1.8.18/jquery-ui.min.js"></script>  

DatePicker의 기본적인 코드는 다음과 같다

$(function() {
  $( "#testDatepicker" ).datepicker({
        buttonImage: "button.png", //옵션
        buttonImageOnly: true      //옵션 
  });
});

DatePicker 에서 사용 가능한 Option은 다음과 같다

DatePicker 옵션

Each

jQuery - each() 메서드 $.each(object, function(index, item){});
배열과 length속성을 갖는 배열과 유사 배열 객체들을 index를 기준으로 반복할 수 있습니다.
첫번째 매개변수로 배열이나 객체를 받으며, 두번째 매개변수로 콜백함수를 받습니다.

var obj = { 
  daum: 'http://www.daum.net'
  , naver: 'http://www.naver.com'
};
$.each(obj, function(index, item){
  var result = '';
  result += index + ' : ' + item;
  console.log(result);
}]
출력 결과
daum : http://www.daum.net
naver : http://www.naver.com

$(selector).each(function(index, item{});

<ul cliass="list">
    <li>Lorem ipsum dolor sit amet.</li>
    <li>Lorem ior sit amet.</li>
    <li>Lorem ipsum </li>
<ul>
 
$('.list li').each(function(idex, item){
    $(item).addClass('li_0' + index);
    // or
    $(this).addClass('li_0' + index);
});

continue, break 방법

 

jQuery each loop를 돌명서 continue, break 하는 방법

jQuery API 정복 - 선택된 요소만큼 루프, each()

Format

In jQuery, what's the best way of formatting a number to 2 decimal places?

<script type="text/javascript">
 
    // mini jQuery plugin that formats to two decimal places
    (function($) {
        $.fn.currencyFormat = function() {
            this.each( function( i ) {
                $(this).change( function( e ){
                    if( isNaN( parseFloat( this.value ) ) ) return;
                    this.value = parseFloat(this.value).toFixed(2);
                });
            });
            return this; //for chaining
        }
    })( jQuery );
 
    // apply the currencyFormat behaviour to elements with 'currency' as their class
    $( function() {
        $('.currency').currencyFormat();
    });
 
</script>   
<input type="text" name="one" class="currency"><br>
<input type="text" name="two" class="currency">

Json

Map function for objects (instead of arrays)

myObject = { 'a':1, 'b':2, 'c':3 };
newObject = myObject.map(function (value, label) {
    return value*value;
});
 
// newObject is now { 'a':1, 'b':4, 'c':9 }

Radio

jQuery select, radio의 disabled 설정
How to reset radiobuttions in jQuery so that none is checked

Old Way(pre-1.6)
$('input[name="${name}"]').attr('checked', false);
New War(1.6+)
$('input[name="${name}"]').prop('checked', false);

https://stackoverflow.com/questions/977137/how-to-reset-radiobuttons-in-jquery-so-that-none-is-checked

Validate radio buttons

var valid = false;
$('#formName').find(':input:radio').each(function(){
    if($(this).prop('checked'))
        valid = true;
});
 
if(!valid)
  return false;

Validate radio buttons with jquery?

[jQuery] 라디오버튼 및 텍스트박스 비활성화시키기 "readonly" "disabled"

String 생성, 변경하기

Converting a value to string in javascript

1. value.toString()
2. "" + value
3. String(value)

https://2ality.com/2012/03/converting-to-string.html

Select

text로 선택하기

var selected_text = '111111';
$("#S option").filter(function() { return (this.text==selected_text); }).attr('selected', true);

select box 옵션을 text로 선택하기

Trigger(트리거)

Plugin

Tip

Troubleshooting

Ref

Case Study(jQuery Note)

jquery 자신을 포함한 html 가져오기


$('selector').wrap("<div/>").parent().html();  // div가 있는 경우
$('selector').parent().html();   // 적용   
/var/services/web/dokuwiki/data/pages/wiki/javascript/jquery.txt · 마지막으로 수정됨: 2023/01/13 18:44 (바깥 편집)