jQuery 정리 03
22 Feb 2019
Reading time ~6 minutes
jQuery 정리 03 - Form Control 값 설정/ 얻기, HTML에 속성 추가, 태그 추가/삭제
Form Control 값 설정/ 얻기
- 값 얻기
var selecteorsValue = $("selector").val();
- 값 설정
$("selector").val(값);
- jQuery에서 태그에 접근할 때 사용하는게 id
- 그러나 jsp나 servlet으로 form 값을 전달할 땐 name이 더 중요!
- 값 얻기 예
<div id="getValue">
<strong>값 얻기</strong>
<form name="frm" id="frm" action="test.jsp">
<label>text</label>
<input type="text" name="text" value="오늘부터 우리는" id="text" class="inputBox"><br/>
<label>password</label>
<input type="password" name="pass" value="여자친구" id="pass" class="inputBox"><br/>
<label>hidden</label>
<input type="hidden" name="hid" value="2019-02-22" id="hid" class="inputBox"><br/>
<label>checkbox</label><!-- value가 없는 checkbox는 선택되면 "on"이 넘어간다. -->
<input type="checkbox" name="flag" id="flag">로그인유지<br/>
<label>날짜선택</label><!-- HTML5에서 지원되는 Control -->
<input type="date" name="date" id="date"><br/>
<label>지역선택</label>
<select name="loc" id="loc">
<option value="서울">서울</option>
<option value="경기">경기</option>
<option value="강원">강원</option>
<option value="충청">충청</option>
</select><br/>
<label>파일선택</label>
<input type="file" name="file" id="file" class="inputBox"><br/>
<label>TA</label>
<textarea class="inputBox" name="ta" id="ta" style="width:300px; height:100px;">소원,은하,엄진,유주,신비,예린</textarea><br/>
<input type="button" value="값얻기" class="btn" id="btn">
<input type="reset" value="초기화" class="btn">
</form>
<div id="showValue"></div>
</div>
// 이름이 유일한 HTML Form Control 얻기
$("#btn").click(function() {
var output = "<ul>";
output += "<li>text:"+$("#text").val()+"</li>"; // text 값 얻기
output += "<li>pass:"+$("#pass").val()+"</li>"; // password 값 얻기
output += "<li>hidden:"+$("#hid").val()+"</li>"; // hidden 값 얻기
output += "<li>checkbox:"+$("#flag").val()+"</li>"; // checkbox 값 얻기
// value가 없으면 "on"이 나온다.
output += "<li>date:"+$("#date").val()+"</li>"; // date 값 얻기
output += "<li>loc:"+$("#loc").val()+"</li>"; // select 값 얻기
output += "<li>file:"+$("#file").val()+"</li>"; // file 값 얻기
// 가상의 경로명(fakepath)이 나온다.(ie는 모든 경로 나옴)
output += "<li>textarea:"+$("#ta").val()+"</li>"; // textarea 값 얻기
output+="</ul>";
$("#showValue").html(output);
if(confirm("전송하시겠습니까?")){
// document.frm == $("#frm")
// 폼이름으로 태그를 찾기 == jQuery를 사용 id로 태그 찾기
$("#frm").submit();
}
});
- 값 설정 예
<div id="setValue">
<strong>값 설정</strong>
<form name="frm1" id="frm1">
<label>text</label>
<input type="text" name="text" id="text1" class="inputBox"><br/>
<label>password</label>
<input type="password" name="pass" id="pass1" class="inputBox"><br/>
<label>hidden</label>
<input type="hidden" name="hid" id="hid1" class="inputBox"><br/>
<label>checkbox</label><!-- value가 없는 checkbox는 선택되면 "on"이 넘어간다. -->
<input type="date" name="date" id="date1"><br/>
<label>파일선택</label>
<input type="file" name="file" id="file1" class="inputBox"><br/>
<label>TA</label>
<textarea class="inputBox" name="ta" id="ta1" style="width:300px; height:100px;"></textarea><br/>
<input type="button" value="값설정" class="btn" id="btnSet">
<input type="reset" value="초기화" class="btn">
</form>
</div>
$("#btnSet").click(function() {
$("#text1").val("김정윤"); // text 값 설정
$("#pass1").val("123456"); // pass 값 설정
$("#hid1").val("히든태그의 값"); // hidden 값 설정
// date 값 설정, yyyy-mm-dd의 형식을 가진다.
$("#date1").val("2019-02-25");
// file 값 설정, file은 값 설정이 되지 않는다!
// $("#file1").val("c:/dev/env.bat"); // X
var msg = "널 향한 설레임은\n 오늘부터 우리는";
$("#ta1").val(msg); // textarea 값 설정
});
HTML의 속성 추가
- checkbox를 체크되도록 설정
- 속성을 변경해야 됨, attr함수나 prop함수 사용
// attr, 속성이 추가만 되고 변경이 안된다.
$("selector").attr("속성명","값");
// prop, 속성 추가되고 변경도 된다.
$("selector").prop("속성명","값");
checkbox의 check 상태
- is() 함수를 사용
$("selector").is(":checked"); // true 또는 false 반환
- id는 유니크해야 되기 때문에 class나 name selector로 찾는다.
<input type="checkbox" name="hobby" value="a"/>a
<input type="checkbox" name="hobby" value="b"/>a
<input type="checkbox" name="hobby" value="c"/>a
<input type="checkbox" name="hobby" value="d"/>a
var arr = $("[name='hobby']");
$.each(arr, function(idx, cb) {
if($(cb).is(":checked")) { // $(cb) == $(this), this는 가장 가까운 객체
// 체크된 객체의 값을 얻을 수 있음
}
});
- checkbox 선택 상태 예
<div>
<label>감상영화선택</label><br/>
<input type="checkbox" name="movie" value="사바하">사바하<br/>
<input type="checkbox" name="movie" value="극한직업">극한직업<br/>
<input type="checkbox" name="movie" value="해리포터와 비밀의방">해리포터<br/>
<input type="checkbox" name="movie" value="신데렐라">신데렐라<br/>
<input type="button" value="선택한 값 얻기" class="btn" id="btn">
</div>
<div id="movieView"></div>
$(function() {
$("#btn").click(function() {
// 체크박스 중 선택된 제목을 얻는다.
// 이름이 같은 Control들은 배열로 처리된다.
var checkArr = $("[name='movie']");
var output = "<ul>";
$.each(checkArr, function(idx, cb) {
if($(this).is(":checked")) { // $(cb) == $(this), jQuery
output += "<li>"+$(this).val()+"</li>";
}
/* if (cb.checked) { // HTML
output += "<li>"+cb.value+"</li>";
} */
});
output += "</ul>"
$("#movieView").html(output);
});
});
- 선택된 영화의 synopsis내용도 보여주기
- 영화명과 시놉시스를 담는 JSONArray 생성
$(function() {
$("#btn").click(function() {
// 체크박스 중 선택된 제목을 얻는다.
var checkArr = $("[name='movie']"); // 이름이 같은 Control들은 배열로 처리된다.
var data = "[ { 'movie' : '해리포터', 'synopsis':'해리포터가 비밀의 방에 들어가기 위해 비밀번호를 찾아 나가는데...' },"
+ "{ 'movie' : '사바하', 'synopsis' : '가나다라 마바사바하!!'}, "
+ "{ 'movie' : '극한직업', 'synopsis' : '마약반 형사가 지금까지 이런 맛은 없었다.. 새로운 마약을 발견하는 영화...'}, "
+ "{ 'movie' : '신데렐라', 'synopsis' : '신데렐라가 유리구두를 잃어버리고 마는데...'} ]";
var output = "<ul>";
var movieJsonArr = eval("("+data+")");
$.each(checkArr, function(idx, cb) {
if($(this).is(":checked")) { // $(cb) == $(this)
checkMovie = $(this).val(); // 할당해서 쓰면 매번 HTML에 접근 안해도 됨
output += "<li>"+checkMovie+"</li>";
// 선택된 영화의 줄거리를 가지고 있는 JSONArray에서 값 얻기
$.each(movieJsonArr, function(idx, movieJson) {
if (movieJson.movie == checkMovie) { // 여기서 this를 쓰면 movieJson이 됨
output += "<li> "+movieJson.synopsis+"</li>";
}
});
}
});
output += "</ul>"
$("#movieView").html(output);
});
});
- 라디오 버튼으로 선택된 포스터의 이미지를 보여주기
<div>
<label>감상영화선택</label><br/>
<input type="radio" name="movie1" value="harry">해리포터와 비밀의방<br/>
<input type="radio" name="movie1" value="sabaha">사바하<br/>
<input type="radio" name="movie1" value="extreme">극한직업<br/>
<input type="radio" name="movie1" value="cinderella">신데렐라<br/>
<input type="button" value="포스터보기" class="btn" id="btn1">
</div>
<div>
<img id="img">
</div>
$("#btn1").click(function() {
var radioArr = $("[name='movie1']");
// checkbox와 다르게 radio는 하나만 선택가능, 검색이 필요없다.
var imgName = $("[name='movie1']:checked").val();
if (imgName == undefined) { // 선택된게 없으면 undefined
alert("영화를 선택해주세요.");
return;
}
/* 배열을 반복시켜 선택된 라디오가 존재한다면 값을 얻음
var imgName = "";
$.each(radioArr, function(idx, radio) {
if ($(this).is(":checked")) { // this == radio
imgName = $(this).val();
}
});*/
// img태그에 속성 설정
$("#img").attr("src","images/"+imgName+".png");
});
- attr()과 prop() 차이 예
- attr을 사용하면 속성 추가가능, 수정 불가
- 전체선택, 해제 속성을 줄 순 있으나 다시 선택, 해제 값을 줄 수 없음
- prop은 속성 추가, 수정 가능
- 전체선택, 해제 속성을 주고 반복해서 선택, 해제 값으로 수정가능
- 속성값을 줄 땐 attr보단 prop함수를 사용권장
- attr을 사용하면 속성 추가가능, 수정 불가
<div>
<label>감상영화선택</label><br/>
<input type="checkbox" name="flag" id="flag">전체선택</br>
<input type="checkbox" name="movie" value="해리포터">해리포터와 비밀의방<br/>
<input type="checkbox" name="movie" value="사바하">사바하<br/>
<input type="checkbox" name="movie" value="극한직업">극한직업<br/>
<input type="checkbox" name="movie" value="신데렐라">신데렐라<br/>
<input type="button" value="선택한 값 얻기" class="btn" id="btn">
</div>
$("#flag").click(function() {
var flag = $(this).is(":checked");
var movieArr = $("[name='movie']");
$.each(movieArr, function(idx, movie) {
// name="movie"인 체크박스의 체크 상태를 변경하는 속성 추가
// $(movie).attr("checked",flag); // attr() - 속성 추가 가능, 수정 불가
$(movie).prop("checked",flag); // prop() - 속성 추가, 수정 가능
});
})
태그 추가/삭제 (DOM 관련 함수)
- html(), text()가 DOM 관련 함수(이전시간 공부)
- 추가 버튼을 누르면 테이블의 행이 추가되는 기능을 구현가능
- div 또는 tr이 추가되는 경우가 많음
- append함수를 사용
- 태그를 삭제할 땐 remove함수를 사용
$("selector").append("추가할 내용"); // 추가된 내용 덧붙임
$("selector").remove(); // 추가된 내용 삭제
- 태그 추가/삭제 예1
<div>
<label>이름</label>
<input type="text" name="name" id="name" class="inputBox"><br/>
<label>나이</label>
<input type="text" name="age" id="age" class="inputBox"><br/>
<label>주소</label>
<input type="text" name="addr" id="addr" class="inputBox"><br/>
<input type="button" value="행 추가" class="btn" id="btnInput">
<input type="button" value="마지막행 삭제" class="btn" id="btnRemove">
</div>
<table border='1' id='tab'>
<tr>
<th width="80">이름</th>
<th width="40">나이</th>
<th width="200">주소</th>
</tr>
</table>
$(function() {
$("#btnInput").click(function() {
// 입력값으로 table에 행 추가
var name=$("#name").val();
var age=$("#age").val();
var addr=$("#addr").val();
$("table:last").append("<tr><td>"
+name+"</td><td>"+age+"</td><td>"
+addr+"</td></tr>"); // 행 추가
$("#name").val("");
$("#age").val("");
$("#addr").val("");
});
});
$("#btnRemove").click(function() {
$("#tab:last tr:last").remove(); // table의 마지막 tr 마지막을 삭제
});
- 첫 행의 삭제 막기
$(function() {
var cnt = 0;
$("#btnInput").click(function() {
// 입력값으로 table에 행 추가
var name=$("#name").val();
var age=$("#age").val();
var addr=$("#addr").val();
$("#tab:last").append("<tr><td>"
+name+"</td><td>"+age+"</td><td>"
+addr+"</td></tr>");
$("#name").val("");
$("#age").val("");
$("#addr").val("");
cnt++;
});
$("#btnRemove").click(function() {
if (cnt > 0) {
$("#tab:last tr:last").remove();
cnt--;
}
});
});
- 또 다른 해결 방법
$("#btnRemove").click(function() {
// $("table tr").length는 행의 개수를 반환
if ($("#tab tr").length > 1) { // 첫 행 뒤에 추가됐다면 지우기
$("#tab:last tr:last").remove();
}
});
- 태그 추가/삭제 예2
<div id="licenseDiv" style="width:500px;">
<div>
<span style="float:left">자격사항</span>
<span style="float:right">
<a href="#void"><img src="images/add.png" title="자격사항 추가" id="l_add"></a>
<a href="#void"><img src="images/remove.png" title="자격사항 삭제" id="l_remove"></a>
</span>
</div>
</div>
<div id="licenseFrm"></div>
$("#l_add").click(function() { // 자격사항 추가(+)
// 입력 폼 추가
if ($("#licenseFrm div").length < 5) {
var output = "<div>자격증명 <input type='text' style='inputBox' name='license' class='inputBox'><br/>"
+"취득일 <input type='date' name='l_date'> "
+"발급기관 <input type='text' style='inputBox' class='inputBox' name='auth'></div>";
$("#licenseFrm").append(output);
} else {
alert("자격증은 5개까지만 입력가능합니다.");
}
});
$("#l_remove").click(function() { // 자격사항 삭제(-)
$("#licenseFrm div:last").remove();
// $("#licenseFrm").children().last().remove(); // 위와 동일한 기능
});