728x90

게시글 작성 및 수정 작업 중 @Valid 를 사용하지 않고 자바스크립트를 통해 form 데이터를 검증하도록 하였다.

관련 프로젝트 : https://black-mint.tistory.com/70

 

[Spring Boot] 게시글 작성, 수정

이전 파일 업로드 글과 연관지어 게시글 작성의 구현을 마무리하고 이를 정리하겠습니다. 파일첨부에 대해서는 언급하지 않겠습니다! 이전 글 : https://black-mint.tistory.com/62?category=982467 [Spring Boot].

black-mint.tistory.com


1. html 코드

			<form action="#" th:action="@{/board/form}" th:object="${board}" method="post" enctype="multipart/form-data"
				onsubmit="return checkForm(this);">
				<div class="mb-3">
					<label for="title" class="form-label">제목</label>
					<input type="text" class="form-control" id="title" th:field="*{title}">
				</div>
				<div class="mb-3">
					<label for="content" class="form-label">내용</label>
					<textarea class="form-control" id="content" rows="13" th:field="*{content}"></textarea>
				</div>

				<div class="nav justify-content-end mb-5">
					<button id="submit" type="submit" class="me-2 btn btn-primary">작성</button>
				</div>
			</form>
  • onsubmit을 이용해 form 양식 제출 시 값을 검증한다.
  • checkForm(this) : this를 넣어줌으로써 자바스크립트에서 form 태그에 담긴 데이터를 컨트롤하는데 용이

2. 검증 script 코드

		// form submit 검증
		function checkForm(form) {
			if (form.title.value == "") {
				alert('제목을 입력하세요.');
				form.title.classList.add('is-invalid');
				form.title.focus();
				return false;
			}

			if (form.content.value == "") {
				alert('내용을 입력하세요.');
				form.title.classList.remove('is-invalid');
				form.content.classList.add('is-invalid');
				form.content.focus();
				return false;
			}
			form.content.classList.remove('is-invalid');
			return true;
		}
  • 파라미터로 넘어온 form(this)를 이용해 값을 확인한다.
  • form.[name].value : 제출된 [name] 이름을 가진 element의 값
  • classList.add : 해당 태그에 클래스를 추가한다.
  • classList.remove : 해당 태그의 클래스를 제거한다.
  • focus() : 해당 태그로 커서를 옮긴다.
  • return false의 경우 서버로 값이 넘어가지 않음.
728x90

특정 버튼을 클릭했을 때 다른 태그의 내용을 보여주고자 한다. 자바스크립트로 태그 내용을 숨겨보자.

또, 숨겼던 태그를 나타내보자.

1. 태그 숨기기

document.getElementById('userList').style.display = "none"
  • document.getElementById로 숨기고자 하는 태그를 가져온다.
  • style.display = "none"으로 숨긴다.

2. 태그 나타내기

document.getElementById('userList').style.display = "block"
  • 위 내용과 동일하게 작성하고 none을 block으로 바꾸면 된다. 

3. 활용

계정생성 버튼을 선택하면 <div id="addDiv">가 나타나고 돌아가기를 클릭하면 <div id="userList>태그가 나타난다.

<div id="userList>
	<a type="button" class="btn btn-primary me-2" onclick="changeDiv()">계정생성</a>
</div>
<div id="addDiv">
	<a type="button" class="btn btn-primary me-2" onclick="changeDiv()">돌아가기</a>
</div>

 

        // 회원 리스트 폼 & 회원 생성 폼 전환
        function changeDiv() {
            var listDiv = document.getElementById('userList');
            var addDiv = document.getElementById('addUser');

            if(listDiv.style.display === 'none') {
                listDiv.style.display = 'block';
                addDiv.style.display = 'none';
            } else {
                listDiv.style.display = 'none';
                addDiv.style.display = 'block';
            }
        }
  • a태그의 타입을 button으로 지정하고 onclick으로 자바스크립트 함수를 호출해준다.
  • 버튼을 누르면 display 상태에 따라 특정 태그를 숨기고 나타낸다.
728x90
$(#comment).html('<spen>댓글</spen>');
  • id값이 comment 인 태그의 요소를 <span>댓글</spen>으로 바꿈

* 출처 : https://www.codingfactory.net/10324

 

jQuery / Method / .html() - 선택한 요소 안의 내용을 가져오거나, 다른 내용으로 바꾸는 메서드

.html() .html()은 선택한 요소 안의 내용을 가져오거나, 다른 내용으로 바꿉니다. .text()와 비슷하지만 태그의 처리가 다릅니다. 문법 1 .html() HTML 태그를 포함하여 선택한 요소 안의 내용을 가져옵니

www.codingfactory.net

 

* 사용 프로젝트 : https://black-mint.tistory.com/35

 

[Spring Boot] Ajax(비동기) 통신으로 댓글 구현 (+ Jquery 사용법)

게시판 댓글을 구현하는 도중 비동기 호출에 대해 알게 됐고, 이를 이용하려면 Ajax를 활용해야 한다는 정보를 얻었다. 비동기란? 비동기의 반대인 동기적 통신의 경우 절차적으로 일을 차례로

black-mint.tistory.com

 

728x90

체크박스에 체크하고 삭제하는 글관리 구현 중 전체 체크박스를 체크하는 기능을 구현한다.

 


1. html 코드

                <table class="table caption-top table-bordered table-hover">
                    <caption>List</caption>
                    <thead>
                        <tr>
                            <th class="text-center" width="50" scope="col">
                                <input type="checkbox" onclick="selectAll(this)">
                            </th>
                            <th class="text-center" width="50" scope="col">No</th>
                            <th class="text-center" width="950" scope="col">제목</th>
                            <th class="text-center" width="200" scope="col">작성일</th>
                            <th class="text-center" width="180" scope="col">작성자</th>
                        </tr>
                    </thead>

                    <tbody>
                        <tr th:each="board : ${boardList}">
                            <td class="mt-5 text-center" scope="row">
                                <div class="checkbox">
                                    <input type="checkbox" name="boardIdList" th:value="${board.id}">
                                </div>
                            </td>
                            <td class="mt-5 text-center" scope="row" th:text="${board.id}">1</td>
                            <td><a th:text="${board.title}" th:href="@{/board/post(boardId=${board.id})}"
                                    style="text-decoration:none; color:black;">제목</a></td>
                            <td class="text-center" th:text="${#dates.format(board.createDate, 'yyyy/MM/dd HH:mm')}">작성일
                            </td>
                            <td class="text-center" th:text="${board.writer}">작성자</td>
                        </tr>
                    </tbody>
                </table>
  • 체크박스에 onclick 이벤트를 달아준다.

2. 스크립트 코드

    <script>
        function selectAll(selectAll) {
            var checkboxs = document.querySelectorAll(['input[type="checkbox"]'])

            checkboxs.forEach((checkbox) => {
                checkbox.checked = selectAll.checked
            })
        }
    </script>
  • document.querySelectorAll : 모든 체크박스 쿼리를 가져옴
  • this로 체크박스를 받았기 때문에 this체크박스가 체크되면 모든 체크박스가 체크되도록 코드 작성

* 출처 : https://hianna.tistory.com/432

728x90
            var boardIdList = []

            $('input[name="boardIdList"]:checked').each(function (i) {
                boardIdList.push($(this).val());
            });
  • 이름이 boardIdList인 input태그의 체크된 값을 가져옴.
  • each로 반복하여 체크 개수만큼 push

* 출처 https://hanke-r.tistory.com/24

 

JavaScript - 체크박스 다중선택 value값

체크박스 다중선택 value값 가져오기 $("input[name=tblChk]:checked").each(function(){ var test = $(this).val(); console.log("체크된 값 : " + test); }); 체크박스 다중선택 value값 배열에 담기 var arTest..

hanke-r.tistory.com

 

728x90

서버에서 Json 형태로 프론트로 넘어오면 날짜 형식이 다음과 같이 변경돼서 날아온다.

"createDate""Jan 5, 2022, 4:25:48 PM"

원하는 날짜 형식으로 바꿔 보여주고 싶을 때 사용할 라이브러리

https://momentjs.com/

 

Moment.js | Home

Format Dates moment().format('MMMM Do YYYY, h:mm:ss a'); moment().format('dddd'); moment().format("MMM Do YY"); moment().format('YYYY [escaped] YYYY'); moment().format(); Relative Time moment("20111031", "YYYYMMDD").fromNow(); moment("20120620", "YYYYMMDD"

momentjs.com

사용법

<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
  • 스크립트를 추가하고 사용하면된다.
moment(변수).format("YYYY-MM-DD HH:mm:ss")
  • 사용 문법

* 적용 프로젝트

https://black-mint.tistory.com/50

 

[Spring Boot] 댓글 기능 - REST API 규칙 적용

저번에 작성한 댓글 기능 구현 코드를 REST API 규칙에 맞게 수정하도록한다. * 이전 댓글 구현 글 https://black-mint.tistory.com/35 [Spring Boot] Ajax(비동기) 통신으로 댓글 구현 (+ Jquery 사용법) 게시판..

black-mint.tistory.com

 

728x90

1. 자바스크립트 빈 문자열 검사 함수

function isEmpty(strIn)
{
    if (strIn === undefined)
    {
        return true;
    }
    else if(strIn == null)
    {
        return true;
    }
    else if(strIn == "")
    {
        return true;
    }
    else
    {
        return false;
    }
}

* 출처 : https://stackoverflow.com/questions/19592721/isempty-is-not-defined-error

 

isEmpty is not defined-error

I was getting an error as isEmpty is not defined .what i have to do .while alerting too it is not showing any alert. <!DOCTYPE html> <html> <head> ...

stackoverflow.com

2. 활용

        function insertComment() {
            var boardId = $('input[name=boardId]').val()
            var content = document.getElementById("content").value;

            if (isEmpty(content) == true) {
                alert('댓글을 입력해주세요.')
                return false;
            } else {
                $.ajax({
                    type: 'POST',
                    url: '/board/comment/write',
                    data: {
                        boardId: boardId,
                        content: content
                    },
                    success: function (response) {
                        getComments()
                        console.log("insert success")
                    },
                    error: function (response) {
                        console.log("insertComment error : " + response)
                    },
                })
            }
        }
  • 댓글 추가 ajax 코드
  • 댓글 내용 없이 작성버튼을 클릭하면 경고문을 띄우고 리턴.
728x90
$('input[name=a]').after("<button onclick=\"getComments()\">취소</button>")
  • $('선택 태그').after("")
728x90

1. 이름으로 태그 불러오기

$('ul[name=commentChange]').hide()
  • <ul> 태그의 name이 commentChange인 태그를 숨긴다.

2. 태그 숨기기

$('pre[name=comment' + commentId + ']').contents().unwrap().wrap('<p></p>')
  • <pre>태그의 name이 comment + commentId(댓글 번호, 특정 댓글 태그만 변경하기 위한 값) 인 태그를 <p>태그로 바꿈
728x90

1. 확인창

if (confirm("정말 삭제하시겠습니까?")) {
	// 확인 클릭시
} else { // 취소 클릭 시
	return;
}

2. 팝업창 띄우기

alert('hello')

 

+ Recent posts