티스토리 뷰

<input type="text" name="id">
<input type="submit">

input 태그가 하나일 때는 enter 키를 누르면 자동으로 submit이 됩니다 ! 위와 같은 경우죠.

<input type="text" name="id">
<input type="password" name="pw">
<input type="submit">

하지만 이렇게 input 태그가 두 개 이상일 때에는 enter 키를 누르면 submit이 되지 않습니다. 이럴 때는 스크립트로 처리를 해줘야 하는데요! 아래 코드를 참조하시면 됩니다.

 

1. enter 키를 누르면 특정한 이벤트가 일어나도록 함수를 호출하는 법

<form action="index2.html" method="POST">
    <input type="text" class="id" placeholder="아이디" onkeypress="press(this)">
    <br>
    <input type="password" class="pw" placeholder="패스워드" onkeypress="press(this)">
    <input type="submit" value="확인" class="submit" onclick="login()">
</form>

<script>
	function login(){
        var id = $(".main .grid li .list li .login .id").val();
        var pw = $(".main .grid li .list li .login .pw").val();
        
        if(id == '123' && pw == '123'){
            location.href = 'index2.html';
        }else{
            alert("아이디/비밀번호를 확인하세요.")
        }
    } //submit을 눌렀을 때 실행되어야 할 함수입니다.

    function press(f){
        if(f.keyCode == 13){
            login();
        }
    } //enter 키는 13번, enter를 눌렀을 때 login() 함수를 호출
</script>

 

2. enter 키를 누르면 form를 submit 시키기

<form action="index2.html" method="POST" name="myForm">
    <input type="text" class="title" placeholder="title" onkeypress="press(this)">
    <br>
    <input type="text" class="content" placeholder="content" onkeypress="press(this)">
    <input type="submit" value="확인" class="submit">
</form>

<script>
    function press(f){
        if(f.keyCode == 13){
            myForm.submit()
        }
    } //enter 키는 13번, enter를 눌렀을 때 myForm를 submit 시키기
</script>