form안에 버튼이 여러 개일 때, 특정 버튼 눌렀을 때만 제출하게 하기

sangeun jo·2022년 4월 17일
0

사내결재사이트

목록 보기
4/7

1. 문제

이런 폼이 있다고 해보자. 이미지를 업로드하고 크롭을 한 다음 제출해야한다.

<!DOCTYPE html>
<html>
    <body>
        <form action="/req/submit" method="POST" >
            ...
            <button id="crop">사진 크롭</button>
            <button id="submit" type="submit" ></button></input>
        </form>
    </body>
</html>

그런데 사진 크롭 버튼을 누르면 그냥 제출되어버린다. 다음과같이 사진 크롭버튼을 밑으로 빼면?

<!DOCTYPE html>
<html>
    <body>
        <form action="/req/submit" method="POST" >
            ...
            <button id="submit" type="submit" ></button></input>
        </form>
        <button id="crop">사진 크롭</button>
    </body>
</html>

제출 버튼 밑에 사진 크롭버튼이 있어서 안 예쁘다.

2. 해결 방안

실제 제출버튼을 안보이게 숨기고, 페이크버튼과 크롭버튼을 form 바깥으로 뺀다.
페이크 버튼을 누르면 실제 제출 버튼이 눌리게 하면 된다.

<!DOCTYPE html>
<html>
    <body>
        <form action="/req/submit" method="POST" >
            ...
            <button style="display:none;" id="submit" type="submit" >진짜 제출 버튼</button>
        </form>
        <button id="crop">사진 크롭</button>
        <button onclick="submit();">가짜 제출 버튼</button>
        <script>
            function submit() {
                document.getElementById("submit").click();
            };
        </script>
    </body>
</html>

3. 더 간단한 해결 방안

button 태그(사진크롭)를 input 태그로 바꾸고 onclick이벤트를 할당한다..

<input onclick="function()">
profile
코더가 아니라 개발자가 되자

0개의 댓글