Input 안에 버튼 - Input an-e beoteun

take it into account

button 태그


form 태그 안에 form data와 관련 없는 버튼을 만든 후 그 버튼을 눌렀더니 form이 전송되는 경우가 있는데,

이는 button 태그의 type속성의 default값이 submit 이기 떄문입니다.

사실 button태그의 type 속성 값들은 input 태그의 type 속성 값들과 겹칩니다.

button 태그의 type 속성 값인 submit, reset, button 은 input 태그의 type 속성으로도 사용할 수 있습니다.

그럼에도 불구하고, 더 다양한 type을 제공하는 input을 사용하지 않고, button을 사용하는 이유는 다음과 같습니다.


button 태그의 type 속성


button 태그의 type속성값은 submit, reset, button 이 있습니다.

submit은 폼을 제출하는 이벤트를 발생시킵니다.

reset은 폼안에 작성된 내용을 초기화시킵니다.

button은 그 자체로는 아무런 이벤트가 없고, click이벤트와 연결시켜서 자바스크립트를 활용하는 방법을 많이 사용합니다.

 즉, form에서 활용할 수 있는 태그입니다.


button vs input


button 스스로 닫지 않는 태그

input   스스로 닫는 태그

따라서 button은 하위 태그들을 추가할 수 있는 반면에 input은 그럴 수가 없습니다.

예를 들어, 폼의 제출 버튼에 이미지를 삽입한다고 하면 button태그를 사용하는 경우 button의 자식으로 img태그를 넣어주면 간편하게 해결이 됩니다.

하지만 input 태그를 사용한다면 img태그를 사용할 수 없고, css의 background-image를 사용해야 합니다.

또한, 이미지는 img태그를 사용하는 것이 검색엔진 최적화등에 도움이 된다는 사실이 있습니다.


출처 : https://cocoder16.tistory.com/18?category=1173631 

[HTML & CSS] input과 button의 공통점과 차이점

button 태그가 하는 일은 무엇일까? "어느 날 이런 일을 겪었다. form 태그 안에 form data와 관련 없는 버튼을 만든 후 그 버튼을 눌렀더니 form이 전송되었다. 응? button을 눌렀는데 왜 form이 "submit" 되지

cocoder16.tistory.com

Input 안에 버튼 - Input an-e beoteun

아래 코드를 돌려보면 이유를 알수 있습니다. 

input form에서 엔터를 쳤을때.

1번 : 반응없음 

2번 : submit

3번 : button의 이벤트 발생 (여러개일때 가장 앞의 버튼의 이벤트 호출)

4번 : 반응없음.

FORM 안에 BUTTON을 사용한다면 type="button" 속성을 추가해야 합니다.


<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" > <title>button test</title> </head> <body class="account-save-page"> <h5>1. input밖에 없음.</h5> <form> <input type="text"> <input type="text"> <input type="text"> </form> <h5>1. input 과 버튼 (이벤트 없음.)</h5> <form> <input type="text"> <input type="text"> <input type="text"> <button>클릭</button> </form> <h5>1. input 과 버튼 (click 이벤트 있음)</h5> <form> <input type="text"> <input type="text"> <input type="text"> <button onclick="javascript:alert('alert!')">클릭</button> </form> <h5>1. input 과 버튼 속성 type="button"(click 이벤트 있음)</h5> <form> <input type="text"> <input type="text"> <input type="text"> <button type="button" onclick="javascript:alert('alert!')">클릭</button> </form> </body>

http://www.w3schools.com/tags/tag_button.asp 참조.

If you use the <button> element in an HTML form, different browsers may submit different values. Use <input> to create buttons in an HTML form.

button type = { button | submit | reset } 이고 브라우저마다 default type이 다를수 있네요. 
글고 IE8 Standards mode에서 default type=submit 이라고 하네요.

Remarks
The default value of the type attribute depends on the current document compatibility mode. The default value is submit. In other compatibility modes the default value is button.
When the BUTTON element is submitted in a form, the value depends on the current document compatibility mode.
Windows Internet Explorer 8 and later. The default value of the type attribute depends on the current document compatibility mode. In IE8 Standards mode, the default value is submit. In other compatibility modes and earlier versions of Windows Internet Explorer, the default value is button.

input의 타입을 search로 지정하면 브라우저 내에서 input 초기화 버튼을 넣어줍니다. 

Input 안에 버튼 - Input an-e beoteun
예시 이미지

디자인을 중요시 하는 일부 프로젝트에서는 이것마저 커스텀해주기를 원합니다. 

하지만 사실상 브라우저 내에서 생성하기 때문에 저 자체를 커스텀 할 수는 없고, 이를 보이지 않게 한 뒤 추가로 디자인과 기능을 넣어주면 됩니다. 

약간은 번거로운 작업일 수 있지만 생각보다 간단합니다. 

우선 브라우저 내에서 생성한 초기화 버튼을 없애려면 단순히 input의 타입을 text로 지정하거나 css에서 해결해 줄 수 있습니다. 

/* IE의 경우 */
input::-ms-clear,
input::-ms-reveal{
    display:none;
}
/* 크롬의 경우 */
input::-webkit-search-decoration,
input::-webkit-search-cancel-button,
input::-webkit-search-results-button,
input::-webkit-search-results-decoration{
    display:none;
}

( 테스트 해보니 IE10까지만 먹습니다. )

그리고 div로 한번 감싸고 input옆에 버튼을 추가해 줍니다. 

버튼을 absolute로 붙인 뒤 버튼의 크기만큼 input에 padding을 줘야 input에 글씨를 많이 넣어도 가려지지 않아요.

// html
<div class="inputWrap">
    <input type="search" placeholder="검색어를 입력하세요" />
    <button class="btnClear"></button>
</div>
// css
.inputWrap {
    position: relative;
    height: 30px;
    display: inline-block;
 }
  
.inputWrap input {
  padding-right: 30px;
  height: inherit;
}

.inputWrap .btnClear {
  position: absolute;
  top: 0;
  right: 0;
  width: 30px;
  height: inherit;
  background: url(https://img.icons8.com/pastel-glyph/2x/cancel.png) center center no-repeat;
  background-size: 50%;
  border: none;
  outline: none;
  cursor: pointer;
}

그리고 input의 value를 초기화시켜줄 스크립트를 짜줍니다.

여러 가지 방식이 있겠지만 저는 부모의 자식을 찾아서 없애주는 방식으로 하겠습니다. 

이렇게 하면 형제를 찾는 것보다 이점은 구조의 순서(input과 button)가 바뀌어도 상관이 없고, 복수개를 넣어도 에러가 발생할 일이 없기 때문입니다. 

스크립트는 아래의 소스 둘 중 하나를 선택해서 사용하면 됩니다.

1. addEventListener 

// javascript
// 한개일때
<script>
    var btnClear = document.querySelector('.btnClear');
    btnClear.addEventListener('click', function(){
        btnClear.parentNode.querySelector('input').value = "";
    })
</script>
// javascript
// 여러개일때 
<script>
    var btnClear = document.querySelectorAll('.btnClear');
    btnClear.forEach(function(btn){
        btn.addEventListener('click', function(){
            btn.parentNode.querySelector('input').value = "";
        })
    })
</script>

2. onClick

<div class="inputWrap">
    <input type="search" placeholder="나이를 입력하세요" />
    <button class="btnClear" onClick="clearInput(this)"></button> <!-- onClick 추가 -->
</div>
<script>
    var clearInput = function(obj) {
        obj.parentNode.querySelector('input').value = ""
    }
</script>