본문 바로가기
개발일지/Web Development

jQuery 연습하기

by jungwonyu 2022. 1. 25.
728x90
1. 빈칸 체크 함수 만들기

1-1. 버튼을 눌렀을 때 입력한 글자로 얼럿 띄우기

1-2. 버튼을 눌렀을 때 칸에 아무것도 없으면 "입력하세요!" 얼럿 띄우기

<div class="question-box">
    <h2>1. 빈칸 체크 함수 만들기</h2>
    <h5>1-1. 버튼을 눌렀을 때 입력한 글자로 얼럿 띄우기</h5>
    <h5>[완성본]1-2. 버튼을 눌렀을 때 칸에 아무것도 없으면 "입력하세요!" 얼럿 띄우기</h5>
    <input id="input-q1" type="text"/>
    <button onclick="q1()">클릭</button>
</div>

✏️ 풀이

<script>
        function q1() {
            // 입력값 가져오기
            let txt = $('#input-q1').val();

            // 만약 입력값이 빈칸이면 '입력하세요!' 띄우고 아니라면 입력값 띄우기
            if (txt == "") {
                alert('입력하세요!')
            } else {
                alert(txt)
            }
        }
</script>

 

2. 이메일 판별 함수 만들기

2-1. 버튼을 눌렀을 때 입력받은 이메일로 얼럿 띄우기

2-2. 이메일이 아니면(@가 없으면) '이메일이 아닙니다'라는 얼럿 띄우기

2-3. 이메일 도메인만 얼럿 띄우기

<div class="question-box">
    <h2>2. 이메일 판별 함수 만들기</h2>
    <h5>2-1. 버튼을 눌렀을 때 입력받은 이메일로 얼럿 띄우기</h5>
    <h5>2-2. 이메일이 아니면(@가 없으면) '이메일이 아닙니다'라는 얼럿 띄우기</h5>
    <h5>[완성본]2-3. 이메일 도메인만 얼럿 띄우기</h5>
    <input id="input-q2" type="text"/>
    <button onclick="q2()">클릭</button>
</div>

✏️ 풀이

<script>
	function q2() {
            // 입력값 가져오기
            let txt = $('#input-q2').val();

            // 만약 가져온 값에 @가 있으면 도메인만 추출해서 띄우고, @가 없으면 '이메일이 아닙니다.' 띄우기
            if (txt.includes('@')) {
                let domain = txt.split('@')[1].split('.')[0]
                alert(domain)
            } else {
                alert('이메일이 아닙니다.')
            }
        }
 </script>

✨참고

includes()

split()

 

3. HTML 붙이기/지우기 연습

3-1. 이름을 입력하면 아래 나오게 하기

3-2. 다지우기 버튼을 만들기

<div class="question-box">
    <h2>3. HTML 붙이기/지우기 연습</h2>
    <h5>3-1. 이름을 입력하면 아래 나오게 하기</h5>
    <h5>[완성본]3-2. 다지우기 버튼을 만들기</h5>
    <input id="input-q3" type="text" placeholder="여기에 이름을 입력"/>
    <button onclick="q3()">이름 붙이기</button>
    <button onclick="q3_remove()">다지우기</button>
    <ul id="names-q3">
        <li>세종대왕</li>
        <li>임꺽정</li>
    </ul>
</div>

✏️ 풀이

<script>
        function q3() {
            // 입력값 가져오기
            let txt = $('#input-q3').val();

            // 가져온 값을 이용해서 붙일 태그 만들기
            let temp_html = `<li>${txt}</li>`;
            // 만들어둔 temp_html을 names-q3에 붙이기
            $('#names-q3').append(temp_html);
        }

        function q3_remove() {
            // names-q3의 태그 모두 비우기
            $('#names-q3').empty();
        }
    </script>

✨참고

empty()


아직까지는 할만하고 재밌군 :)