본문 바로가기

국비필기노트/HTML & CSS & JS

JS_cursor,submit(Event)

Cursor

 

커서의 위치에 따라서 event를 수행할 수 있다. 

 

 

1)Change

 

1
2
3
4
5
6
7
8
9
10
11
<p id="result"></p>
    <input type="text" id="target">
    
    <script>
         let t = document.getElementById('target');
         t.addEventListener('change',function(event){
             document.getElementById('result').innerHTML 
             = event.target.value;
         });
         
    </script>
cs

 

Change: 커서가 밖으로 빠져나올 때 function을 실행한다.

text안에서 커서가 밖으로 빠져나오게되면 change가 이를 캐치하여 input에 썼던 내용이 p태그에 innerHTML로 인하여 삽입이 되는 코드다.

 

 

2)focus, blur

 

1
2
3
4
5
6
7
8
9
10
11
    <input type="text" id ="target" />
    
    <script>
        let t= document.getElementByID("target");
        t.addEventListener('blur',function(){
            console.log('blur');
        });
        t.addEventListener('focus',function(){
            console.log('focus');
        });
    </script>
cs

 

focus: 엘리먼트에 포커스가 생겼을 때 함수를 실행한다.

blur: 포커스가 사라졌을 때 함수를 실행한다.

 

 

Submit

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<form action="result.html" id="target">
    <label>
        name: <input type="text" id="name">
        <input type="submit">
    </label>
</form>
 
<script>
    let t = document.getElementById("target");
    t.addEventListener('submit',function(){
        if(document.getElementById("name").value.length == 0){
            alert("Name필드의 값이 누락되었습니다.");
            event.preventDefault();
        }
    })
</script>
cs

 

폼 정보를 서버로 전송하는 명령어인 submit 을 눌렀을 때 해당 event를 form 태그에 적용한 코드이다.

name값이 0일 경우, if문으로 들어가 alert를 구현시킬 수 있다. 이는 아이디나 비밀번호 등 회원가입할 때 주로 사용된다.

'국비필기노트 > HTML & CSS & JS' 카테고리의 다른 글

js_mouse(Event)  (0) 2022.05.25
JS_기본동작의 취소(Event)  (0) 2022.05.24
JS_onclick(Event)  (0) 2022.05.18
JS_document.getElementsByTagName  (0) 2022.05.16
JS_객체(Window, Location, History, Navigator)  (0) 2022.05.16