Theme. 답글 입력 구현하기
jQuery를 활용하여 답글을 작성하고, 등록하는 것을 간단하게 구현해보자.
결과부터 확인해보면,
웹 브라우저의 화면에는 다음과 같이 나타난다.
답글 입력 버튼을 누르게 되면, 답글을 남길 수 있도록 입력창이 나타나고, 이를 등록할 수 있는 버튼이 나타난다.
답글을 작성하고, 답글등록 버튼을 누르면 아래에 그 답글 내용이 나타난다.
버튼을 누르면 이어서 다른 input 태그나 버튼이 나타나도록 하기 위해 append() 메서드를 사용하였다.
<div> 태그 안에 append()를 통해 input태그와 버튼을 이어붙인다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
|
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
</head>
<body>
<h3>detail view</h3>
<textarea rows="3" cols="50">답글 입력버튼을 통해 답글을 남겨주세요</textarea>
<br><br>
<!-- 답글 입력 버튼 -->
<button type="button" id="answerBtn">답글입력</button>
<br>
<div id="answerForm">
<!-- 입력창, 등록버튼 -->
</div>
<p id="demo"></p>
<script>
$(document).ready(function() {
$("#answerBtn").click(function () {
let input = "<br>답글:<input type='text' id='answerText'>";
$("#answerForm").append(input);
let btn = "<br><br><button type='button' id='answer'>답글등록</button>";
$("#answerForm").append(btn);
});
// 답글등록 버튼은 처음 document가 모두 실행된 이후에 추가된 것이므로 아래와 같이 코드를 작성해줘야 한다.
$(document).on("click", "#answer", function() {
let txt = $("#answerText").val();
$("#demo").text(txt);
});
});
</script>
</body>
</html>
|
cs |
이때 주의할 것은 답글등록 버튼은 $(document).ready(function() { } 안에서 클릭 이벤트에 대한 코드를 작성하면 실행되지 않는다는 것이다. 왜냐하면, document가 모두 실행되고 난 뒤 새로 추가된 요소이기 때문이다. 따라서 위와 같이 코드를 작성해 주어야 한다.
Theme. css(), attr()
css()를 통해 디자인의 변경을 하거나 attr()를 통해 속성을 추가할 수 있다.
먼저, 테이블을 만들고, mouseover, mouseout을 할 때, tr 태그 중 class가 "hover"인 tr에 대해서만 css()를 이용해 배경색이 바뀌도록 하면,
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
|
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
</head>
<body>
<table border="1">
<col width="50"><col width="200"><col width="150">
<tr>
<th>번호</th><th>이름</th><th>나이</th>
</tr>
<tr class="hover">
<th>1</th><td>홍길동</td><td>24</td>
</tr>
<tr class="hover">
<th>2</th><td>성춘향</td><td>16</td>
</tr>
<tr>
<th>3</th><td>일지매</td><td>22</td>
</tr>
</table>
<p>p 태그입니다.</p>
<button type="button">버튼</button>
<script>
$(document).ready(function(){
$("tr.hover").mouseover(function(){
$(this).css('background', '#00ff00');
});
$("tr.hover").mouseout(function(){
$(this).css('background', '#ffffff');
});
});
</script>
</body>
</html>
|
cs |
이는 td 태그에 대해서만 적용할 수도 있다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
<script>
$(document).ready(function(){
// $("tr.hover").mouseover(function(){
// $(this).css('background', '#00ff00');
// });
// $("tr.hover").mouseout(function(){
// $(this).css('background', '#ffffff');
// });
$("td").mouseover(function(){
$(this).css('background', '#00ff00');
});
$("td").mouseout(function(){
$(this).css('background', '#ffffff');
});
});
</script>
|
cs |
이제 버튼을 클릭했을 때, p 태그의 배경색, 글자색을 바꿔보자.
버튼을 누르게 되면,
1
2
3
4
5
6
7
|
$('button').click(function(){
$('p').css('background', '#0000ff');
$('p').css('color', '#ffffff');
// 아래와 같이 한번에 작성할 수 있다.
$('p').css({'background':'#00ff00', 'color':'#ffffff'});
});
|
cs |
또한, 버튼 클릭 시 p 태그에 id와 class를 추가할 수 있는데,
$('p').attr('id', 'pid');
$('p').attr('class', 'mycss');
의 형식으로 추가하면 된다.
이 경우 <style> 태그 안에서 css 문법을 통해 p 태그를 클릭하는 등에 대한 이벤트 발생시 효과를 줄 수 있을 것이다.
예를 들면,
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
|
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<style>
.mycss{
background-color: #ff0000;
color: #ffff00;
border: 1px solid;
}
</style>
</head>
<body>
<table border="1">
<col width="50"><col width="200"><col width="150">
<tr>
<th>번호</th><th>이름</th><th>나이</th>
</tr>
<tr class="hover">
<th>1</th><td>홍길동</td><td>24</td>
</tr>
<tr class="hover">
<th>2</th><td>성춘향</td><td>16</td>
</tr>
<tr>
<th>3</th><td>일지매</td><td>22</td>
</tr>
</table>
<p>p 태그입니다.</p>
<button type="button">버튼</button>
<script>
$(document).ready(function(){
$('button').click(function(){
$('p').attr('id', 'pid');
$('p').attr('class', 'mycss');
});
$(document).on('click', '#pid', function (){
alert('pid click');
let id = $('p').attr('id');
alert(id);
});
});
</script>
</body>
</html>
|
cs |
Theme. id, class, name에 대한 jquery 작성 형식
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
|
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
</head>
<body>
<p>Hello Jquery</p>
<p id="id">Hello Jquery</p>
<p class="cls">Hello Jquery</p>
<p name="name1">Hello Jquery</p>
<button type="button">button</button>
<script>
$(document).ready(function(){
$('button').click(function(){
// $('p').hide(); - p 태그에 대해 적용
// $('*').hide(); - 모든 것들에 대해 적용
// $('p#id').hide(); - p 태그 중 id가 "id"인 태그에 대해 적용
// $('p.cls').hide(); - p 태그 중 class가 "cls"인 태그에 대해 적용
$('p[name=name1]').hide(); // p 태그 중 name이 "name1"인 태그에 대해 적용
});
})
</script>
</body>
</html>
|
cs |
Theme. 입력 데이터의 전송
입력 데이터의 전송 방법에는
1. <a> 태그의 이용(<a href = "">)
2. <form> 태그의 이용(<form action="")
3. location.href=""
사용 예시는 아래 코드를 참고한다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
|
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
</head>
<body>
<!-- 입력 데이터 전송
<a href=""
<form action=""
location.href=""
-->
<a href="NewFile.jsp">NewFile로 이동</a>
<br><br>
이름:<input type="text" id="name"><br>
나이:<input type="text" id="age"><br>
주소:<input type="text" id="address"><br>
<button type="button" id="send">버튼</button>
<script>
$(document).ready(function(){
$('#send').click(function() {
let name = $('#name').val();
let age = $('#age').val();
let address = $('#address').val();
location.href = "NewFile.jsp?name=" + name + "&age=" + age + "&address=" + address;
});
});
</script>
<br><br><br>
<form id="frm">
이름:<input type="text" name="name"><br>
나이:<input type="text" name="age"><br>
주소:<input type="text" name="address"><br>
<button type="button" id="btn">전송</button>
</form>
<script>
$(document).ready(function(){
$('#btn').click(function(){
$("#frm").attr("action", "NewFile.jsp").submit();
});
});
</script>
</body>
</html>
|
cs |
NewFile.jsp는
1
2
3
4
5
6
7
8
9
10
11
12
|
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
String name = request.getParameter("name");
int age = Integer.parseInt(request.getParameter("age"));
String address = request.getParameter("address");
System.out.println("이름:" + name);
System.out.println("나이:" + age);
System.out.println("주소:" + address);
%>
|
cs |
Theme. 태그를 새로 추가하는 방법
1. 문자열로 추가
2. JS로 추가
3. jQuery로 추가
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
|
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
</head>
<body>
<div id="demo">
</div>
<br>
<button type="button">버튼</button>
<script type="text/javascript">
$(document).ready(function(){
$("button").click(function(){
// 문자열로 추가
let str = "<p id='pid'>p 태그를 추가합니다</p>";
$("#demo").append(str);
// JavaScript로 추가
let jsStr = document.createElement("h3");
jsStr.setAttribute("id", "h3id");
jsStr.innerHTML = "h3 태그를 추가합니다.";
$("#demo").append(jsStr);
// Jquery 추가
// let jqStr = $("<span></span>").text("span 태그를 추가합니다.");
let jqStr = $("<span>").text("span 태그를 추가합니다.");
jqStr.attr("id", "spanid");
$("#demo").append(jqStr);
});
});
</script>
</body>
</html>
|
cs |
그 결과 버튼을 누르면
Theme. radio, checkbox, select, table의 사용
1.radio
input 태그의 type 중 하나인 radio의 경우 id는 사용할 수 없고, name을 사용해야 한다.
버튼을 누르면,
체크한 항목을 저장하고, 기본적으로 특정 항목이 선택되도록 하는 예시를 살펴보자.
사과를 선택하고 버튼을 클릭했고, 이후 기본적으로 배가 선택된 모습을 확인할 수 있다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
|
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
</head>
<body>
<!-- radio -->
<!-- type이 radio이므로 id는 사용할 수 없고 name을 사용해야 한다-->
<ul>
<li><input type="radio" name="radioTest" value="사과">사과</li>
<li><input type="radio" name="radioTest" value="배">배</li>
<li><input type="radio" name="radioTest" value="바나나">바나나</li>
</ul>
<button type="button" id="btn">선택</button>
<script>
$(document).ready(function(){
$("#btn").click(function(){
// getter
// 체크된 항목이 radioVal에 저장
let radioVal = $("input[name='radioTest']:checked").val();
alert(radioVal);
// setter([] 안에 값을 적어줘야 한다.)
$("input[name='radioTest']").val(["배"]); // 버튼 누르면 기본적으로 배가 선택되도록 함
});
});
</script>
</body>
</html>
|
cs |
2. checkbox
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
|
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
</head>
<body>
<!-- checkbox -->
<input type="checkbox" id="ch1" name="ch">그림 그리기
<input type="checkbox" id="ch2" name="ch">음악 듣기
<br><br>
<button type="button" id="cbtn">체크</button>
<script type="text/javascript">
$(document).ready(function(){
$("#cbtn").click(function(){
// getter
let check1 = $("#ch1").is(":checked"); // #ch1이 선택되면 true, 선택되지 않으면 false 반환
alert(check1);
let check2 = $("input:checkbox[id='ch2']").is(":checked"); // #ch2이 선택되면 true, 선택되지 않으면 false 반환
alert(check2);
// setter
// id가 ch1인 박스가 기본적으로 선택되도록
$("#ch1").attr("checked", "checked"); // attribute
$("#ch1").prop("checked", true); // property
});
});
</script>
</body>
</html>
|
cs |
3. select
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
|
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
</head>
<body>
<!-- select -->
<select id="food">
<!-- prepend 시 추가 되는 곳 -->
<option value="햄버거">햄버거</option>
<option value="피자" selected="selected">피자</option>
<option value="치킨">치킨</option>
<!-- append 시 추가 되는 곳 -->
</select>
<p id="demo">선택한 음식이 추가되는 공간</p>
<button type="button" id="sbtn">선택</button>
<button type="button" id="append">추가(뒤에)</button>
<button type="button" id="prepend">추가(앞에)</button>
<script type="text/javascript">
// onchange
$("#food").change(function(){
let val = $(this).val();
$("#demo").html(val); // p 태그의 텍스트 변화
});
// 선택된 항목을 알려줌
$("#sbtn").click(function(){
alert($("#food").val());
});
$("#append").click(function(){
$("#food").append("<option value='스테이크'>스테이크</option>"); // 기존 옵션 맨 마지막 뒤에 옵션 추가
});
$("#prepend").click(function(){
$("#food").prepend("<option value='떡볶이'>떡볶이</option>"); // 기존 옵션 첫번째 앞에 옵션 추가
});
</script>
</body>
</html>
|
cs |
이를 실행해보자.
처음엔 피자가 선택되어 있을 것이다(selected 이용)
햄버거를 선택해보면,
선택 버튼을 누르면,
추가(뒤에) 버튼을 누르고 select 태그의 항목들을 확인해보면,
추가(앞에) 버튼을 누르고 확인해보면,
4. table에 append 활용
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
|
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
</head>
<body>
<table border="1" id="table">
<col width="50"><col width="200"><col width="100">
<tr>
<th>번호</th>
<th>제목</th>
<th>작성</th>
</tr>
<!-- 아래 append를 이용하면 다음과 같이 생성된다.
<tr>
<th>1</th>
<th>오늘은 금요일 입니다</th>
<th>Tom</th>
</tr>
-->
</table>
<script type="text/javascript">
$("#table").append(
$("<tr>").append(
$("<th>").append(1),
$("<td>").append("오늘은 금요일 입니다"),
$("<td>").append("Tom")
)
);
</script>
</body>
</html>
|
cs |
'JavaScript > jQuery' 카테고리의 다른 글
jQuery 기본(1) (2) | 2023.02.02 |
---|