console.log(typeof "some string"); // "string"

 

===>Built-in Methods : 내장 함수

JavaScript 는 string 을 조작하기 위한 내장 함수(Built-in Methods)들이 존재합니다. 이 메소드들을 사용하면 항상 새로운 string 이 생성됩니다. string 이 immutable object 이기 때문입니다.

console.log("hello".charAt(0)); // "h" : 문자열에서 0번째 문자를 반환합니다.

console.log("hello".toUpperCase()); // "HELLO" : 문자열을 대문자로 바꿉니다.

console.log("Hello".toLowerCase()); // "hello" : 문자열을 소문자로 바꿉니다.

console.log("hello".replace(/e|o/g, "x")); // "hxllx" : 문자열에서 e, o 문자를 x 로 바꿉니다.

console.log("1,2,3".split(",")); // ["1", "2", "3"] : 문자열을 , 로 쪼개서 배열에 담습니다.

 

===>Length Property : 문자열 길이 속성

문자열의 길이 속성입니다. 속성이기 때문에 뒤에 () 를 붙이지 않습니다. 아래 내용을 확인해 보세요.

console.log("Hello".length); // 5 console.log("".length); // 0




출처: https://findfun.tistory.com/62?category=383258 [즐거움을 찾자 Find Fun!!]

Posted by useways
,

출처 : https://blog.naver.com/PostView.naver?blogId=stpark89&logNo=221109345492&parentCategoryNo=&categoryNo=&viewDate=&isShowPopularPosts=false&from=postView

 

input 창이 매우 많다..

대략 40개가 넘는다.. .hidden 값까지 50개...........
하나씩 뽑아보려다가 정말 미치는줄 알았음 
그래서 찾은것 !!


일단 이렇게   선언을 해주고 

$(document).ready(function(){ jQuery.fn.serializeObject = function() { var obj = null; try { // this[0].tagName이 form tag일 경우 if(this[0].tagName && this[0].tagName.toUpperCase() == "FORM" ) { var arr = this.serializeArray(); if(arr){ obj = {}; jQuery.each(arr, function() { // obj의 key값은 arr의 name, obj의 value는 value값 obj[this.name] = this.value; }); } } }catch(e) { alert(e.message); }finally {} return obj; };

실세 등록이든, 수정 버튼을 클릭했을때 

//수정 버튼 클릭시 사용하는 객체 var modifyBusinessOrderObj = JSON.stringify($("#modifyBusinessForm").serializeObject()); $.ajax({ ..... type : "POST", contentType : "application/x-www-form-urlencoded;charset=UTF-8", dataType : 'json', data : { 'data' : modifyBusinessOrderObj, }, ........ });

이렇게 하면 json 문자열로 form 내부에 있는것들을 쭉 뽑아준다.  당연 input 태그들에는 name 값 지정해줘야함

이렇게하면 컨트롤러로 날아오는데   받을때 !! 
우리는 HashMap 을 쓰고있어서 ...  
request 에 담겨있는 정보를 일단 HashMap 에 때려넣었다고 가정하고

들어가있는 데이터를 뽑아주는 부분임.  앞단은 우리 프레임워크라 소스 공개를 못함. : )

메서드 ====== ....{ String list = ""; for(String key : paramMap.keySet()){ if(key.equals("data")){ list = paramMap.get(key); } } //json 문자열 HashMap 에 넣기 위한 것 HashMap<String, String> dataMap = null; ObjectMapper mapper = new ObjectMapper(); try{ dataMap = mapper.readValue(list, new TypeReference<Map<String, String>>(){}); } catch (Exception e) { logger.error(e.getMessage()); }

1. 일단 json 문자열 을 String 변수 - list 에 담아둠
2.ObjectMapper 라는 객체를 선언한다.
3.옮겨둘 HashMap 에다가    objectMapper 에 readValue 라는 메서드를 이용하면됨.  : ) 끝

[출처] jquery - form - serializeObject|작성자 피아노치는

'15 jquery > 50 ajax관련' 카테고리의 다른 글

00 data - undefined 체크  (0) 2021.08.03
Posted by useways
,

실제 개발을 하다 보면 

ajax({ ... success : function(data)})....

대부분 저어어어기  function 에 파라미터로 넘어오는 data 를 이용해서 작업을 하게 된다 

이번프로젝트는 vo 말고, HashMap 을 사용하고있는데 ... 
undefined 체크를 매우 많이 해야함....   상세페이지 볼떄 vo 를 그냥 다 List 로 던져줘가지고...

체크 방법

var date = modifyChkDate(data[0].startDate); function modifyChkDate(date){ if(typeof date != 'undefined'){ var year = date.substring(0,4); var month = date.substring(4,6); var day = date.substring(6,8); }else{ return ''; } }

[출처] Ajax - data - undefined 체크|작성자 피아노치는

 

'15 jquery > 50 ajax관련' 카테고리의 다른 글

form - serializeObject  (0) 2021.08.03
Posted by useways
,

알다시피 라디오는 name 으로 묵여서  두개의 라디오버튼 클릭했을때 하나만 선택되는 방식이라
조금 다르다.

$(':input:radio[name=네임값]:checked').val(),

해석을 해보면 ===
필터걸어줘서  inpu 중에 radio 중에 name 이 뭐뭐 인 것중에 
checked 되어있는것의 value 를 뽑는다. 

[출처] jquery - radio value 값 뽑기|작성자 피아노치는

Posted by useways
,

http://tiger5net.egloos.com/5667935

https://kanetami.tistory.com/32

 

 

1. jQuery로 선택된 값 읽기

 

$("#selectBoxoption:selected").val();

$("select[name=name]").val();

$("#select_box > option:selected").val()

 

2. jQuery로 선택된 내용 읽기

 

$("#selectBoxoption:selected").text();

$('#select_box > option[value='+selValue+']').text();

 

3. 선택된 위치

 

var index =$("#test option").index($("#test option:selected"));

 

-------------------------------------------------------------------

 

4. Addoptions to the end of a select  항목 추가

 

$("#selectBox").append("<optionvalue='1'>Apples</option>");

$("#selectBox").append("<optionvalue='2'>After Apples</option>");

 

5. Addoptions to the start of a select 항목 맨 첫 위치에 추가

 

$("#selectBox").prepend("<optionvalue='0'>Before Apples</option>");

 

6. Replaceall the options with new options 전체 option 변경

 

$("#selectBox").html("<optionvalue='1'>Some oranges</option><option value='2'>MoreOranges</option>");

 

7. Replaceitems at a certain index 지정된 index 위치의 option 변경

 

$("#selectBoxoption:eq(1)").replaceWith("<option value='2'>Someapples</option>");

$("#selectBoxoption:eq(2)").replaceWith("<option value='3'>Somebananas</option>");

 

8. 지정된 index값으로 select 하기

 

$("#selectBoxoption:eq(2)").attr("selected", "selected");

 

9. text 값으로 select 하기

 

$("#selectBox").val("Someoranges").attr("selected", "selected");

 

$("#select_box > option[@value=지정값]").attr("selected", "true");

 

10. value값으로 select 하기

 

$("#selectBox").val("2");

 

 

보통은 컨트롤로에서 플래그를 주고 selected 를 제어했는데

이번엔 좀 특이한 케이스여서 jQuery 로 제어하게 되었내요

1
2
3
<select id="flag">
    <option value="1">선택</option>
</select>
 

예시로 이러한 SelectBox 가 존재할 경우에 value 값이 '1' 인 옵션을 selected 시켜주고 싶으면

1 $("#flag").val("1").prop("selected"true);  

이런식으로 사용해주면 됩니다.

추가로 '이외의 옵션을 선택하지 않는다'의 경우는 의미가 없는 생각이므로

true 를 따로 false 로 해서 코딩해줄 필요가 없습니다

 

 

11. 지정된 인덱스값의 item 삭제

 

$("#selectBoxoption:eq(0)").remove();

 

12. 첫번째 item 삭제

 

$("#selectBoxoption:first").remove();

 

13. 마지막 item 삭제

 

$("#selectBoxoption:last").remove();

 

14. 선택된 옵션의 text 구하기

 

alert(!$("#selectBoxoption:selected").text());

 

15. 선택된 옵션의 value 구하기

 

alert(!$("#selectBoxoption:selected").val());

 

16. 선택된 옵션 index 구하기

 

alert(!$("#selectBoxoption").index($("#selectBox option:selected")));

 

17. SelecBox 아이템 갯수 구하기

 

alert(!$("#selectBoxoption").size());

 

18. 선택된 옵션 앞의 아이템 갯수

 

alert(!$("#selectBoxoption:selected").prevAl!l().size());

 

19. 선택된 옵션 후의 아이템 갯수

 

alert(!$("#selectBoxoption:selected").nextAll().size());

 

20. Insertan item in after a particular position

 

$("#selectBoxoption:eq(0)").after("<option value='4'>Somepears</option>");

 

21. Insertan item in before a particular position

 

$("#selectBoxoption:eq(3)").before("<option value='5'>Someapricots</option>");

 

22. Gettingvalues when item is selected

 

$("#selectBox").change(function(){

           alert(!$(this).val());

           alert(!$(this).children("option:selected").text());

});

 

출처 : http://blog.daum.net/twinsnow/124

Posted by useways
,



//결제 방식 for(var i = 0; i < $('#mApproveMethodPop option').size(); i++){ if($('#mApproveMethodPop option:eq('+i+')').val() == data[0].APPROVE_METHOD){ $('#mApproveMethodPop option:eq('+i+')').attr("selected", "selected"); } }

일단 그려져 있는 selectbox 에 접근해서 opton 의 개수만큼 for 문을 돌린다

만약 selectbox 의 option 의 i 번째놈의 value 가  서버로부터 넘어온 데이터와 같다면
selected 해줌 .  끝

[출처] jquery - selectbox selected (일반적인거말고)|작성자 피아노치는

Posted by useways
,
  1. 2012/07/20 UI Droppable, 이미지 갤러리 휴지통 기능 구현 (8)
  2. 2012/07/20 Droppable, visual 효과 처리, revert 기능 제어
  3. 2012/07/20 Droppable, 드롭 기본사용, 드롭 비활성, 전달 방지
  4. 2012/07/11 Draggable, 핸들러 제어, 드래그 + 정렬(Sortable) 기능
  5. 2012/07/10 Draggable, 드래그 Delay 주기, snap효과, 복원
  6. 2012/07/10 Draggable, 드래그 기본사용, 이벤트 제어, 움직임 제한
  7. 2012/07/02 jQuery.unique(), DOM 요소 배열에서 중복된 노드를 제거
  8. 2012/07/02 jQuery.type(), object 타입 알아내기
  9. 2012/07/02 jQuery.trim(), 양쪽 끝 공백 제거
  10. 2012/07/02 jQuery.removeData(), 데이터를 제거
  11. 2012/07/02 jQuery.parseXML(), XML 문서를 파싱
  12. 2012/07/02 jQuery.parseJSON(), JSON 문자열을 JavaScript object로 변환
  13. 2012/07/02 jQuery.now(), 현재 시간을 number로 반환 (2)
  14. 2012/07/02 jQuery.merge(), 두 개의 배열을 합치기
  15. 2012/07/02 jQuery.map(), 새로운 배열 요소로 변경
  16. 2012/07/02 jQuery.makeArray(), 자바스크립트 배열로 변환
  17. 2012/07/02 jQuery.isXMLDoc(), XML 문서인지 확인
  18. 2012/07/02 jQuery.isWindow(), Window 인지 확인
  19. 2012/07/02 jQuery.isPlainObject(), object인지 확인
  20. 2012/07/02 jQuery.isNumeric(), 숫자인지 확인 (2)
  21. 2012/07/02 jQuery.isFunction(), JavaScript 함수인지 확인 (2)
  22. 2012/07/02 jQuery.isEmptyObject(), 객체가 empty 인지 확인
  23. 2012/07/02 jQuery.isArray(), 배열인지 확인
  24. 2012/07/02 jQuery.inArray(), 배열 내의 값을 찾아서 인덱스를 반환
  25. 2012/07/02 jQuery.grep(), 배열 요소를 찾아 걸러내기
  26. 2012/07/02 jQuery.extend(), 두개 이상의 객체를 합치기(Merge)
  27. 2012/07/02 jQuery.each(), 일반적인 반복 함수
  28. 2012/07/02 serializeArray(), 폼 요소를 names와 values 배열로 인코딩
  29. 2012/07/02 serialize(), 폼 요소 집합을 인코딩
  30. 2012/07/02 jQuery.post(), Ajax HTTP POST 방식 요청
  31.  
  32. 2012/07/02 jQuery.param(), Ajax 데이터용 배열이나 객체를 직렬화
  33. 2012/07/02 load(), Ajax로 받은 HTML을 일치하는 요소 안에 추가
  34. 2012/07/02 jQuery.getScript, JavaScript 파일을 로드하고 실행
  35. 2012/07/02 jQuery.getJSON, JSON 데이터를 로드 (1)
  36. 2012/06/19 jQuery.get() HTTP GET 방식 Ajax 요청
  37. 2012/06/19 ajaxSuccess() Ajax 요청이 성공적으로 완료 때마다 호출
  38. 2012/06/19 ajaxStop() Ajax 요청이 완료되면 호출
  39. 2012/06/19 ajaxStart() Ajax 요청이 시작될 때 호출되는 함수
  40. 2012/06/19 jQuery.ajaxSetup() Ajax 옵션 값을 설정하는 함수
  41. 2012/06/19 ajaxSend() Ajax 요청을 보내기 전에 호출되는 이벤트
  42. 2012/06/19 jQuery.ajaxPrefilter() $.ajax() 함수 호출 전 Ajax 옵션 수정
  43. 2012/06/19 ajaxError() Ajax 에러가 발생되면 호출
  44. 2012/06/15 ajaxComplete() Ajax가 완료되면 호출 (4)
  45. 2012/06/12 jQuery.ajax() HTTP 비동기 데이터 교환
  46. 2012/05/08 toggle(), 요소 표시 또는 숨기기, 토글하기
  47. 2012/05/08 jQuery .stop(), 애니메이션 효과 멈춤
  48. 2012/04/25 slideUp(), 슬라이드 효과로 숨기기
  49. 2012/04/25 slideToggle(), 슬라이드 토글하기
  50. 2012/04/25 slideDown(), 슬라이드 효과로 보이기
  51. 2012/04/25 show(), 요소 보이게 하기
  52. 2012/04/25 queue(), 대기열의 함수와 대기열 조작하기
  53. 2012/04/19 hide(), 요소 숨기기 (2)
  54. 2012/04/19 jQuery.fx.off, 전체 애니메이션 효과 전역 설정
  55. 2012/04/16 jQuery.fx.interval, 에니메이션 프레임 조절
  56. 2012/04/16 fadeToggle(), 페이드 인/아웃 토글 (2)
  57. 2012/04/16 fadeTo(), 투명도를 조절하기
  58. 2012/04/16 fadeOut(), 서서히 사라지게 하기
  59. 2012/04/16 fadeIn(), 서서히 나타나게 하기
  60. 2012/04/16 dequeue(), 대기열의 다음 함수 실행 (2)
  61. 2012/04/16 delay(), 대기열의 함수 실행을 지연시키기
  1. 2012/04/16 clearQueue(), 대기열의 함수를 제거
  2. 2012/03/30 animate(), 요소를 움직이기 (6)
  3. 2012/03/20 unload(), 페이지에서 벗어날 때
  4. 2012/03/20 undelegate(), 바인딩 해제하기
  5. 2012/03/20 unbind(), 바인딩 해제하기
  6. 2012/03/20 triggerHandler(), 하나의 함수만 실행시키기
  7. 2012/03/20 trigger(), 함수 실행시키기
  8. 2012/03/09 toggle(), 토글하기
  9. 2012/03/09 submit(), 폼 전송 이벤트
  10. 2012/03/09 select(), 텍스트 드래그 이벤트 (2)
  11. 2012/03/06 scroll(), 스크롤 이벤트 (3)
  12. 2012/03/06 resize(), 사이즈 바꾸기
  13. 2012/03/06 ready(), 문서가 준비되면 실행하기
  14. 2012/02/24 one(), 이벤트 발생하면 바인딩 자동해제 (3)
  15. 2012/02/24 on(), 이벤트 바인딩 하기
  16. 2012/02/24 off(), 이벤트 해제하기
  17. 2012/01/13 jQuery API - mouseup(), 마우스를 눌렀다 뗄 때
  18. 2012/01/13 jQuery API - mouseover(), 마우스가 올라올 때 (3)
  19. 2012/01/13 jQuery API - mouseout(), 마우스가 떠날 때 (2)
  20. 2012/01/13 jQuery API - mousemove(), 마우스가 요소에서 움직일 때
  21. 2012/01/13 jQuery API - mouseleave(), 마우스가 요소에서 벗어날 때
  22. 2012/01/04 jQuery API - mouseenter(), 마우스 진입 감지 이벤트
  23. 2012/01/04 jQuery API, mousedown, 마우스 누름 이벤트
  24. 2012/01/04 jQuery API - load(), 로드되면 발생하는 이벤트
  25. 2011/12/26 jQuery API - live(), 이벤트 바인딩하기
  26. 2011/12/26 jQuery API 정복 - keyup(), 키를 눌렀다 뗄때
  27. 2011/12/26 jQuery API 정복 - keypress(), 브라우져의 키 누름 이벤트
  28. 2011/12/26 jQuery API 정복 - keydown(), 키보드 누름 이벤트 (2)
  29. 2011/12/26 jQuery API 정복 - hover(), 마우스 오버 이벤트
  30. 2011/12/13 jQuery API 정복 - focus(), 요소에 포커스 주기
  31.  
  32. 2011/12/13 jQuery API 정복 - event.timeStamp, 이벤트 사이의 시간
  33. 2011/12/13 jQuery API 정복 - event.target, 이벤트가 발생한 요소
  34. 2011/12/13 jQuery API 정복 - event.pageY, 마우스 Y 좌표
  35. 2011/12/13 jQuery API 정복 - event.pageX, 마우스 X 좌표
  36. 2011/12/08 jQuery API 정복 - die(), 이벤트 해제하기 (2)
  37. 2011/12/08 jQuery API 정복 - delegate(), 이벤트 바인딩하기 (1)
  38. 2011/11/25 jQuery API 정복 - 더블클릭 이벤트, dblclick() (4)
  39. 2011/11/25 jQuery API 정복 - 클릭 이벤트, click()
  40. 2011/11/24 jQuery API 정복 - 변경 이벤트, change()
  41. 2011/11/24 jQuery API 정복 - 포커스 잃을 때 이벤트, blur() (1)
  42. 2011/11/23 jQuery API 정복 - 이벤트 연결하기, bind() (4)
  43. 2011/11/22 jQuery API 정복 - 요소 별로 감싸기, wrapAll()
  44. 2011/11/22 jQuery API 정복 - 넓이 구하기, width()
  45. 2011/11/22 jQuery API 정복 - 요소 감싸기, wrap()
  46. 2011/11/22 jQuery API 정복 - 감싼 요소 제거하기, unwrap()
  47. 2011/11/22 jQuery API 정복 - class 토글하기, toggleClass()
  48. 2011/11/22 jQuery API 정복 - 텍스트만 알아내기, text() (5)
  49. 2011/11/22 jQuery API 정복 - 수직 스크롤 이동, scrollTop() (2)
  50. 2011/11/22 jQuery API 정복 - 수평 스크롤 이동, scrollLeft()
  51. 2011/11/22 jQuery API 정복 - 요소 바꾸기, replaceWith()
  52. 2011/11/22 jQuery API 정복 - 요소 바꾸기, replaceAll() (2)
  53. 2011/11/22 jQuery API 정복 - property 제거, removeProp()
  54. 2011/11/22 jQuery API 정복 - 클래스 제거, removeClass()
  55. 2011/11/22 jQuery API 정복 - 속성 제거, removeAttr()
  56. 2011/11/22 jQuery API 정복 - 요소 제거, remove()
  57. 2011/11/22 jQuery API 정복 - 선택된 모든 요소의 앞에 추가하기2, prependTo()
  58. 2011/11/22 jQuery API 정복 - 선택된 모든 요소의 앞에 추가하기, prepend()
  59. 2011/11/22 jQuery API 정복 - 상대 좌표 구하기, position()
  60. 2011/11/22 jQuery API 정복 - border 포함 넓이 구하기, outerWidth()
  61. 2011/11/22 jQuery API 정복 - border포함 높이 구하기, outerHeight()
  62.  
  63. 2011/11/22 jQuery API 정복 - 좌표 찾기, offset()
  64. 2011/11/22 jQuery API 정복 - 앞에 추가하기, insertBefore()
  65. 2011/11/22 jQuery API 정복 - 뒤에 추가하기, insertAfter()
  66. 2011/11/22 jQuery API 정복 - padding을 포함한 넓이 제어, innerWidth()
  67. 2011/11/22 jQuery API 정복 - padding 포함 높이 제어, innerHeight()
  68. 2011/11/22 jQuery API 정복 - 요소 높이 제어, height()
  69. 2011/11/22 jQuery API 정복 - 텍스트 비우기, empty()
  70. 2011/11/22 jQuery API 정복 - 요소 제거, detach() (2)
  71. 2011/11/22 jQuery API 정복 - 속성을 제어, css()
  72. 2011/11/22 jQuery API 정복 - 요소 복사하기, clone()
  73. 2011/11/22 jQuery API 정복 - 앞에 추가하기, before() (1)
  74. 2011/07/26 jQuery API 정복 - 새로운 요소 추가, appendTo() (4)
  75. 2011/07/20 jQuery API 정복 - 마지막 자식 요소 추가, append() (3)
  76. 2011/07/14 jQuery API 정복 - 뒤에 추가하기, after()
  77. 2011/07/07 jQuery API 정복 - 범위로 자르기, slice()
  78. 2011/07/06 jQuery API 정복 - 형제 요소들 찾기, siblings
  79. 2011/07/05 jQuery API 정복 - 이전에 있는 것들, prevAll()
  80. 2011/07/05 jQuery API 정복 - 이전 요소 찾기, prev()
  81. 2011/06/30 jQuery API 정복 - 특정 조건을 만날 때까지 이전 요소들을 쭈욱, prevUntil()
  82. 2011/06/29 jQuery API 정복 - 특정 부모를 찾을 때까지, parentsUntil()
  83. 2011/06/29 jQuery API 정복 - position으로 부모 찾기, offsetParent()
  84. 2011/06/28 jQuery API 정복 - 부모들 찾기, parents()
  85. 2011/06/28 jQuery API 정복 - 부모 찾기, parent()
  86. 2011/06/27 jQuery API 정복 - ~가 아닌 것, not() (4)
  87. 2011/06/22 jQuery API 정복 - 조건이 맞을 때까지 쭈욱, nextUntil()
  88. 2011/06/21 jQuery API 정복 - 현재 요소의 다음 요소 모두, nextAll()
  89. 2011/06/09 jQuery API 정복 - 현재 요소의 바로 다음 요소, next()
  90. 2011/06/08 jQuery API 정복 - 결과를 배열로 돌려받기, map() (3)
  91. 2011/05/31 jQuery API 정복 - 마지막 요소 찾기, last()
  92. 2011/05/30 jQuery API 정복 - 맞는지 확인하기, is() (4)
    1. 2011/05/25 jQuery API 정복 - 가지고 있나 없나? has() (2)
    2. 2011/05/24 jQuery API 정복 - 첫번째 요소 찾기, first() (2)
    3. 2011/05/19 jQuery API 정복 - 하위 요소 전부 찾기, find() (2)
    4. 2011/05/12 jQuery API 정복 - 선택 요소 집합에서 추출하기, filter() (8)
    5. 2011/05/02 jQuery API 정복 - 인덱스로 요소 찾기, eq() (4)
    6. 2011/04/29 jQuery API 정복 - 이전 선택요소로 돌아가기, end() (2)
    7. 2011/04/28 jQuery API 정복 - 선택된 요소만큼 루프, each() (4)
    8. 2011/04/26 jQuery API 정복 - 텍스트 노드를 포함한 자식요소 가져오기, contents() (4)
    9. 2011/04/21 jQuery API 정복 - 현재 요소에서 가장 가까운 선택 요소, closest() (1)
    10. 2011/04/07 jQuery API 정복 - 자식 요소들 찾기, children() (2)
    11. 2011/03/24 jQuery API 정복 - 선택된 요소들 이어 붙이기, andSelf() (6)
    12. 2011/03/21 jQuery API 정복 - 선택요소 확장하기, add() (2)
    13. 2011/03/17 jQuery API 정복 - 폼의 value 가져오기, val() (4)
    14. 2011/03/15 jQuery API 정복 - 클래스 토글하기, toggleClass (5)
    15. 2011/03/14 jQuery API 정복 - 클래스 제거, removeClass() (2)
    16. 2011/03/11 jQuery API 정복 - 속성 제거, removeAttr()
    17. 2011/03/10 jquery API 정복 - innerHTML 과 같은 표현, html() (10)
    18. 2011/03/03 jQuery API 정복 - 클래스가 있나 찾기, hasClass() (5)
    19. 2011/02/25 jQuery API 정복 - attr(), 속성을 제어하기 (2)
    20. 2011/02/25 jQuery API 정복 - addClass(), 클래스 추가하기 (4)
    21. 2011/02/24 jQuery API 정복 - 눈에 보이는 요소 찾기 : visible (5)
    22. 2011/02/24 jQuery API 정복 - text 박스 찾기 : text (2)
    23. 2011/02/22 jQuery API 정복 - submit 버튼 찾기 : submit (4)
    24. 2011/02/22 jQuery API 정복 - select 박스에서 선택된 것 찾기 : selected (4)
    25. 2011/02/21 jQuery API 정복 - reset 버튼 찾기 : reset (2)
    26. 2011/02/21 jQuery API 정복 - radio 버튼 찾기 : radio (2)
    27. 2011/02/18 jQuery API 정복 - type=password 인 것 찾기 : password (2)
    28. 2011/02/18 jQuery API 정복 - 다른 요소를 포함한 요소 찾기 : parent (2)
    29. 2011/02/17 jQuery API 정복 - 유일한 자식 요소 찾기 : only-child (8)
    30. 2011/02/17 jQuery API 정복 - 홀수번째 요소 찾기 : odd
    1. 2011/02/16 jQuery API 정복 - n번째 자식요소 찾기 : nth-child (4)
    2. 2011/02/16 jQuery API 정복 - ~이 아닌 요소 선택하기 : not (3)
    3. 2011/02/15 jQuery API 정복 - 다음 형제 요소 찾기 : next ~ siblings (4)
    4. 2011/02/14 jQuery API 정복 - 다음 요소 선택하기 : prev + next (5)
    5. 2011/02/14 jQuery API 정복 - 한번에 여러 요소 선택하기 : Multiple Selector (2)
    6. 2011/02/12 jQuery API 정복 - 다중 속성 필터를 이용한 요소 선택 : Mutiple Attribute Selector (2)
    7. 2011/02/12 jQuery API 정복 - 마지막 자식 요소 찾기 : last (2)
    8. 2011/02/11 jQuery API 정복 - 마지막 자식 요소들 찾기 : last-child (2)
    9. 2011/02/11 jQuery API 정복 - 폼에 속한 input 들 선택하기 : jQuery(':input')
    10. 2011/02/10 jQuery API 정복 - image 폼 요소 찾기 : jQuery(":image")
    11. 2011/02/10 jQuery API 정복 - ID 로 찾아내기 : jQuery("#id") (7)
    12. 2011/02/10 jQuery API 정복 - 안보이는 요소 찾기 : jQuery(':hidden') (1)
    13. 2011/02/09 jQuery API 정복 - 제목 태그(h1)를 찾자 : jQuery(':header') (8)
    14. 2011/02/09 jQuery API 정복 - 자식 중에 태그 찾기 : jQuery(':has(selector)') (30)
    15. 2011/02/08 jQuery API 정복 - 속성이 있는지 찾기 : jQuery('[attribute]') (10)
    16. 2011/02/08 jQuery API 정복 - 내용이 빈 태그 찾기 : jQuery(':empty') (7)
    17. 2011/02/07 jQuery API 정복 - 요소명(태그)으로 찾기 : jQuery('element')
    18. 2011/02/07 jQuery 1.5 버젼이 나왔습니다!! (8)
    19. 2011/02/07 jQuery API 정복 - ~보다 작은 요소 선택하기 : jQuery(':lt(index)') (7)
    20. 2011/02/01 jQuery API 정복 - ~보다 큰 요소 선택하기 : jQuery(':gt(index)') (3)
    21. 2011/01/31 jQuery API 정복 - 첫번째 요소 찾기 : jQuery(':first')
    22. 2011/01/31 jQuery API 정복 - 첫째 자식(?) 찾기 : jQuery(':first-child') (3)
    23. 2011/01/29 jQuery API 정복 - input file 찾기 : jQuery(':file')
    24. 2011/01/28 jQuery API 정복 - 리스트 짝수,홀수 찾기 : jQuery(':even') (2)
    25. 2011/01/28 jQuery API 정복 - 인덱스로 요소 찾기 : jQuery(':eq(index)') (6)
    26. 2011/01/28 jQuery API 정복 - 사용 불가 상태 선택하기 : jQuery(':disabled') (2)
    27. 2011/01/27 jQuery API 정복 - 자식 요소 선택하기 : jQuery('ancestor descendant') (2)
    28. 2011/01/27 jQuery API정복 - 특정 단어 포함 요소 선택하기 : jQuery(':contains(text)') (6)
    29. 2011/01/27 jQuery API 정복 - 클래스명으로 선택하기 : jQuery('.class') (4)
    1. 2011/01/27 jQuery 쉽게하기 - API 깨부시기, 선택자(Selector) : 하위 요소 선택 ("parent > child") (8)
    2. 2011/01/26 jQuery 쉽게하기 - API 깨부시기, 선택자(Selector) : 체크된 체크박스만 알아내기 (4)
    3. 2011/01/26 jQuery 쉽게하기 - API 깨부시기, 선택자(Selector) : 체크박스를 찾자 (6)
    4. 2011/01/25 jQuery 쉽게하기 - API 깨부시기, 선택자(Selector) : button 을 찾자 (3)
    5. 2011/01/24 jQuery 쉽게하기 - API 깨부시기, 선택자(Selector) : [name^="value"] (4)
    6. 2011/01/24 jQuery 쉽게하기 - API 깨부시기, 선택자(Selector) : [name!="value"] (5)
    7. 2011/01/22 jQuery 쉽게하기 - API 깨부시기, 선택자(Selector) : [name="value"] (7)
    8. 2011/01/22 jQuery 쉽게하기 - API 깨부시기, 선택자(Selector) : [name$="value"] (2)
    9. 2011/01/21 jQuery 쉽게하기 - API 깨부시기, 선택자(Selector) : [name~="value"] (2)
    10. 2011/01/21 jQuery 쉽게하기 - API 깨부시기, 선택자(Selector) : [name*="value"] (2)
    11. 2011/01/20 jQuery 쉽게하기 - API 깨부시기, 선택자(Selector) : [name|="value"] (2)
    12. 2011/01/20 jQuery 쉽게하기 - API 깨부시기, 선택자(Selector) : ":animated" (9)
    13. 2011/01/19 jQuery 쉽게하기 - API 깨부시기, 선택자(Selectors) : All Selector ("*") (14)
    14. 2011/01/19 jQuery 쉽게하기 - API 깨부시기, jQuery Core (12)
    15. 2011/01/18 jQuery 쉽게하기 - 기본부터 시작하자, 함수(Function) 편 (4)
    16. 2011/01/18 jQuery 쉽게하기 - 기본부터 시작하자, 배열(Array) 편 (4)
    17. 2011/01/17 jQuery 쉽게하기 - 기본부터 시작하자, Object 편 (8)
    18. 2011/01/17 jQuery 쉽게하기 - 기본부터 시작하자, Number 편 (14)
    19. 2011/01/14 jQuery 쉽게하기 - 기본부터 시작하자, string 편 (11)
    20. 2011/01/14 jQuery 쉽게하기 - 파이어폭스의 파어어버그 사용하여 디버깅하기 (6)
    21. 2011/01/13 jQuery 쉽게하기 - 다른 라이브러리와 같이 쓰기 (12)
    22. 2011/01/13 jQuery 쉽게하기 - 자주 묻는 질문과 답변, 두번째 (11)
    23. 2011/01/12 jQuery 쉽게하기 - 자주 묻는 질문과 답변, 그 첫번째 (9)
    24. 2011/01/11 jQuery 쉽게하기 - jQuery 어떻게 쓰는 건가요? (48)
    25. 2011/01/10 jQuery 쉽게하기 - jQuery 를 다운받아 보자. (12)
    26. 2011/01/10 jQuery 쉽게하기 - Documentation 의 Main Page (13)
    27. 2011/01/06 JQuery 쉽게하기 - 시작하기에 앞서 (33)


    출처: https://kanetami.tistory.com/69?category=511677 
Posted by useways
,

http://drst3in.webdoor.co.kr/tc/228

jQuery로 Ajax를 어떻게 쉽게 사용할 수 있는지 보도록 하겠습니다..

jQuery.ajax(settings)

$.ajax(settings)


기본 사용법은 이렇습니다.. 파라미터로 넘어가는 settings 안에서 모든것을 처리하면 됩니다.
settings에 사용되는 속성들을 한번 보겠습니다.

asyncBoolean
Default: true

By default, all requests are sent asynchronous (i.e. this is set to true by default). If you need synchronous requests, set this option to false. Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation. Note that synchronous requests may temporarily lock the browser, disabling any actions while the request is active.

beforeSend(XMLHttpRequest)Function

A pre-callback to modify the XMLHttpRequest object before it is sent. Use this to set custom headers etc. The XMLHttpRequest is passed as the only argument. This is an Ajax Event. You may return false in function to cancel the request.

cacheBoolean
Default: true, false for dataType 'script' and 'jsonp'

If set to false it will force the pages that you request to not be cached by the browser.

complete(XMLHttpRequest, textStatus)Function

A function to be called when the request finishes (after success and error callbacks are executed). The function gets passed two arguments: The XMLHttpRequest object and a string categorizing the status of the request ("success""notmodified""error","timeout", or "parsererror"). This is an Ajax Event.

contentTypeString
Default: 'application/x-www-form-urlencoded'

When sending data to the server, use this content-type. Default is "application/x-www-form-urlencoded", which is fine for most cases. If you explicitly pass in a content-type to $.ajax() then it'll always be sent to the server (even if no data is sent). Data will always be transmitted to the server using UTF-8 charset; you must decode this appropriately on the server side.

contextObject

This object will be made the context of all Ajax-related callbacks. For example specifying a DOM element as the context will make that the context for the complete callback of a request, like so:

$.ajax({ url: "test.html", context: document.body, success: function(){
        $(this).addClass("done");
      }});

 

dataObject, String

Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests. See processData option to prevent this automatic processing. Object must be Key/Value pairs. If value is an Array, jQuery serializes multiple values with same key based on the value of the traditional setting (described below).

dataFilter(data, type)Function

A function to be used to handle the raw responsed data of XMLHttpRequest.This is a pre-filtering function to sanitize the response.You should return the sanitized data.The function gets passed two arguments: The raw data returned from the server, and the 'dataType' parameter.

dataTypeString
Default: Intelligent Guess (xml, json, script, or html)

The type of data that you're expecting back from the server. If none is specified, jQuery will intelligently try to get the results, based on the MIME type of the response (an XML MIME type will yield XML, in 1.4 JSON will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be returned as a string). The available types (and the result passed as the first argument to your success callback) are:

  • "xml": Returns a XML document that can be processed via jQuery.
  • "html": Returns HTML as plain text; included script tags are evaluated when inserted in the DOM.
  • "script": Evaluates the response as JavaScript and returns it as plain text. Disables caching unless option "cache" is used. Note: This will turn POSTs into GETs for remote-domain requests.
  • "json": Evaluates the response as JSON and returns a JavaScript object. In jQuery 1.4 the JSON data is parsed in a strict manner; any malformed JSON is rejected and a parse error is thrown. (See json.org for more information on proper JSON formatting.)
  • "jsonp": Loads in a JSON block using JSONP. Will add an extra "?callback=?" to the end of your URL to specify the callback.
  • "text": A plain text string.

 

error(XMLHttpRequest, textStatus, errorThrown)Function

A function to be called if the request fails. The function is passed three arguments: The XMLHttpRequest object, a string describing the type of error that occurred and an optional exception object, if one occurred. Possible values for the second argument (besides null) are "timeout", "error", "notmodified" and "parsererror". This is an Ajax Event.

globalBoolean
Default: true

Whether to trigger global Ajax event handlers for this request. The default is true. Set to false to prevent the global handlers like ajaxStart or ajaxStop from being triggered. This can be used to control various Ajax Events.

ifModifiedBoolean
Default: false

Allow the request to be successful only if the response has changed since the last request. This is done by checking the Last-Modified header. Default value is false, ignoring the header. In jQuery 1.4 this technique also checks the 'etag' specified by the server to catch unmodified data.

jsonpString

Override the callback function name in a jsonp request. This value will be used instead of 'callback' in the 'callback=?' part of the query string in the url. So{jsonp:'onJsonPLoad'} would result in 'onJsonPLoad=?' passed to the server.

jsonpCallbackString

Specify the callback function name for a jsonp request. This value will be used instead of the random name automatically generated by jQuery. It is preferable to let jQuery generate a unique name as it'll make it easier to manage the requests and provide callbacks and error handling. You may want to specify the callback when you want to enable better browser caching of GET requests.

passwordString

A password to be used in response to an HTTP access authentication request.

processDataBoolean
Default: true

By default, data passed in to the data option as an object (technically, anything other than a string) will be processed and transformed into a query string, fitting to the default content-type "application/x-www-form-urlencoded". If you want to send a DOMDocument, or other non-processed data, set this option to false.

scriptCharsetString

Only for requests with "jsonp" or "script" dataType and "GET" type. Forces the request to be interpreted as a certain charset. Only needed for charset differences between the remote and local content.

success(data, textStatus, XMLHttpRequest)Function

A function to be called if the request succeeds. The function gets passed three arguments: The data returned from the server, formatted according to the 'dataType' parameter; a string describing the status; and the XMLHttpRequest object (available as of jQuery 1.4). This is an Ajax Event.

timeoutNumber

Set a local timeout (in milliseconds) for the request. This will override the global timeout, if one is set via $.ajaxSetup. For example, you could use this property to give a single request a longer timeout than all other requests that you've set to time out in one second. See$.ajaxSetup() for global timeouts.

traditionalBoolean

Set this to true if you wish to use the traditional style of param serialization.

typeString
Default: 'GET'

The type of request to make ("POST" or "GET"), default is "GET". Note: Other HTTP request methods, such as PUT and DELETE, can also be used here, but they are not supported by all browsers.

urlString
Default: The current page

A string containing the URL to which the request is sent.

usernameString

A username to be used in response to an HTTP access authentication request.

xhrFunction

Callback for creating the XMLHttpRequest object. Defaults to the ActiveXObject when available (IE), the XMLHttpRequest otherwise. Override to provide your own implementation for XMLHttpRequest or enhancements to the factory.

 

이것들이 파라미터 안에 사용될수 있는 속성들 입니다... 참 많습니다...

이걸 다 읽기 전에 사용법 보고 나서.. 차근 차근 보셔되 될것 같습니다... 예제 하나 보시죠..

$.ajax({
  url: 'ajax/test.html',
  success: function(data) {
    $('.result').html(data);
    alert('Load was performed.');
  }
});

 

이게 Ajax 코드 입니다.. 몇줄 되지도 않습니다... 쉽게 사용할 수 있죠?..

코드를 대충 보면.. $.ajax( 는 jQuery의 ajax함수를 사용하는 거고 {}로 쌓여있는 부분이 파라미터 들입니다.
기본적으로 두개를 사용하고 있습니다... 

url : 'ajax/test.html' 이 부분은.. ajax로 호출할 서버의 페이지 주소입니다.. 당연히 무언가를 받아오기 위해서 url를 호출해야 하겠죠... 

success : 이부분은 이벤트로.. 서버에서 결과를 정상적으로 받게되면... 이 이벤트가 호출이 됩니다.
이벤트이기 때문에 .. function(data)로 시작하죠... 그럼.. function(data) 에서 data는 서버에서 보내온 정보라 넘어오게 됩니다. 위의 예제에서는.. html 파일을 호출했으니 html 코드가 왔겠군요...

받은 정보를 $('.result')   class="result"인 엘리먼트의 innerHtml 로 바꾸는 코드입니다.

그럼.. 이벤트에(사이트에서는. .콜백함수라고 하고있습니다.) 어떤것들이 있는지 한번 보겠습니다.

  1. beforeSend is called before the request is sent, and is passed the XMLHttpRequestobject as a parameter.
  2. error is called if the request fails. It is passed the XMLHttpRequest, a string indicating the error type, and an exception object if applicable.
  3. dataFilter is called on success. It is passed the returned data and the value ofdataType, and must return the (possibly altered) data to pass on to success.
  4. success is called if the request succeeds. It is passed the returned data, a string containing the success code, and the XMLHttpRequest object.
  5. complete is called when the request finishes, whether in failure or success. It is passed the XMLHttpRequest object, as well as a string containing the success or error code.

 

5가지의 콜백 함수가 있군요...

beforeSend

는 서버로 요청을 보내기전 호출됩니다.

error

는 호출에 실패하였을때 호출됩니다.

dataFilter

는 ajax를 호출할때 파라미터로 dataType이라는것을 넘겨주게 되는데 이값을 검사하여 호출됩니다.

success

는 서버에서 데이터를 잘 받았을때 호출됩니다.

complate

는 성공이나 실패가나더라도.. 요청이 완료된 상태에서 호출이 됩니다.


dataType

그럼.. dataType이 뭔지 한번 볼까요?...
ajax가 서버로 정보를 요청하고 받을 결과가 어떤 데이터 포멧인지를 지정하는 변수입니다.

기본값을 xml 로 되어 있고 html, json, jsonp, script, text 를 사용할 수 있습니다.

text와 html은 결과 데이터를 그냥 통과시켜 버립니다. 많이 쓰게될 json은 json객체로 결과가 넘어오게 됩니다.
데이터를 배열접근하듯이 쉽게 접근할 수 있습니다.

data

data 속성은 서버로 보낼 post data를 지정하는 속성입니다. 제가 전전장에서 Form 가지고 놀기에서 설명했던 함수를 기억하시는 분이 있겠죠?... 호출하는 url 속성에 get 형식으로 데이터를 넘겨도 되지만.. 많은 데이터를 넘길때는.. data 속성을 사용해서 넣어주면.. post로 넘어가게 됩니다.
post 데이터는 항상 UTF-8로 인코딩 되어서 서버로 전달이 됩니다. data를 넘길때는.. 하나 설정해야 할 속성이 더 있습니다...

contentType 이라는 속성인데 이값을 application/x-www-form-urlencoded로 설정 해주어야 합니다.

기차 자세한 속성들의 정본 사이트를 참조하시면 됩니다... 

그럼.. 예제 를 한번 보겠습니다...

$.ajax({
   type: "GET",
   url: "test.js",
   dataType: "script"
 });

실행할 script 파일을 다운로드 받는 예제입니다.

$.ajax({
   type: "POST",
   url: "some.php",
   data: "name=John&location=Boston",
   success: function(msg){
     alert( "Data Saved: " + msg );
   }
 });

 

POST 형식으로 데이터를 넘겨서 서버에서 저장하고 메시지를 반환하는 예제입니다.

$.ajax({
  url: "test.html",
  cache: false,
  success: function(html){
    $("#results").append(html);
  }
});


var html = $.ajax({
  url: "some.php",
  async: false
 }).responseText;


var xmlDocument = [create xml document];
 $.ajax({
   url: "page.php",
   processData: false,
   data: xmlDocument,
   success: handleResponse
 });
bodyContent = $.ajax({
      url: "script.php",
      global: false,
      type: "POST",
      data: ({id : this.getAttribute('id')}),
      dataType: "html",
      async:false,
      success: function(msg){
         alert(msg);
      }
   }
).responseText;


각 예제들은 사이트에서 확인 가능하며... 속성값들의 설명들을 다시한번 읽어보시기 바랍니다...



===>예제

<script>
function paging(){
    count++;
    
    $.ajax({
        type: 'post'
        , async: true
        , url: "/display.do?cmd=productListAppend&ordFlag="+'${ordFlag}'+"&categoryCd="+categoryCd+"&itemCode="+'${itemCode}'+"&count="+count
        , beforeSend: function() {
             $('#ajax_load_indicator').show().fadeIn('fast'); 
          }
        , success: function(data) {
            var response = data.trim();
            console.log("success forward : "+response);
            // 상품 리스트 할당
            $('#view_list').append(response);
            $('#product_count').html($('#view_list li.thumb').size());
          }
        , error: function(data, status, err) {
            console.log("error forward : "+data);
            alert('서버와의 통신이 실패했습니다.');
          }
        , complete: function() { 
            $('#ajax_load_indicator').fadeOut();
          }
    });
}
</script>

Posted by useways
,

Target text field:

type="text" id="target"/>

 

$("#control").toggle(

           function() {    

                     $('#target').attr("disabled", true);

           },

           function() {    

                     $('#target').removeAttr("disabled"); 

           }

);

 

Target text field:

type="text" id="target"> Disable target

 

$('#readonly').click(

           function() {    

                     if($('#readonly').attr("readonly") == true){

                                $('#readonly').val('');

                                $('#readonly').removeAttr("readonly");    

                     }

           }

);

 

[출처] http://blog.naver.com/findaday/117601025

 

http://blog.naver.com/PostView.nhn?blogId=affectionjs&logNo=140121650809

 

Posted by useways
,

 $("tr[seq] a[href]").click(function() {
             
             alert( $(this).attr("name") );

 

    "<tr height='30' seq='{0}' commentCnt='{4}' depth='{4}'  >" +
  "  <a href='#' name='{0}'>" +
  "  <td width='50'  align='center'> {1} &nbsp;</td>" +


===>위의 html에서 tr[seq] a[href] 의 조건이 선택하는 부분은 tr[seq] 부분이 아니라 a[href] 부분이라서
<a href='#' name='{0}'> 의 값을 가져온다.


===>alert( $(this).attr("name") ); 했을때 undefined 란 것이 나오면
 1. attr 속성에 name이 없는 경우
 2. name 있어도 xml에서 값이 정의 안된경우


==================================================

alert( $("tr[seq] a[seq]").eq(5).attr("width") );    의미는 tr부분에 seq속성이 있어야한다.

Posted by useways
,


textarea에서 개행문자 및 줄띄어쓰기 처리


http://drst3in.webdoor.co.kr/tc/228

var review_contents = $.trim($('#Battlelink_review_write textarea[name="battlelink_review_contents"]').val().replace(/(\r\n|\n|\n\n)/gi,'[split]'));

review_contents=review_contents.replace(/\'/g,"''");
review_contents = review_contents.split("[split]")       

textarea에서 2줄띄어쓰기시에 jquery로 innerHTML하면 오류가 발생하는데

줄간격에서 생기는 문제여서 개고생하다가 처리방법을 찾았다....ㅡㅡ;;
Posted by useways
,

 

 <ul>
    <li>list item 1</li>
    <li>list item 2</li>
    <li>list item 3</li>
    <li>list item 4</li>
    <li>list item 5</li>
  </ul>


$('li').eq(2).css('background-color', 'red');
위 스크립트를 실행하면 item 3 위치의 배경색이 빨간색으로 바뀌게 됩니다

만약 음수값을 인덱스로 사용하게 된다면 리스트의 뒤쪽부터 세어 나가면 됩니다. 아래 예제를 보시죠.
$('li').eq(-2).css('background-color', 'red');

 

Posted by useways
,