ABOUT ME

GoGo!

Today
Yesterday
Total
  • [Javascript] disabled, readonly
    ■ Front-End/- JavaScript & TypeScript 2020. 7. 16. 21:27

     

     

     

     

    로그인 페이지를 개발하던 중, ID input에 이미 저장된 ID 값을 넣어주고 input을 disabled 처리해달라는 요청이 있었다.

    그래서 아래와 같이 코드 한 줄을 git에 푸시했다.

    document.getElementById("inputId").disabled = true;
    

     

     

    그런데 갑자기 옆에서 로그인이 안된다는 이야기가 나왔다.

    확인해보니 로그인할 때 아이디와 비밀번호를 form data로 보내주고 있었는데, id 값이 빠진채로 submit하고 있었다.

    로그인 로직은 고친게 없어서 아무래도 저 disabled가 원인으로 보였다.

     

     

    혹시나하고 구글에 "javascript input disabled form data" 라고 쳐봤더니, 역시나 disabled가 문제였다.

    input 필드 안의 값을 수정할 수 없도록 하기 위해서는 'disabled'와 'read-only'를 사용하는데, 각각 약간 차이가 있다.

    w3schools 사이트에서 'readonly'에 대한 설명을 살펴보면 아래와 같다.

     

     

    The readonly attribute is a boolean attribute.
    When present, it specifies that an input field is read-only.
    A read-only input field cannot be modified (however, a user can tab to it, highlight it, and copy the text from it).
    The readonly attribute can be set to keep a user from changing the value until some other conditions have been met (like selecting a checkbox, etc.). Then, a JavaScript can remove the readonly value, and make the input field editable.
    Note: A form will still submit an input field that is readonly, but will not submit an input field that is disabled!


    'readonly'은 boolean 값으로 된 속성이다. input 필드를 읽기 전용으로 쓰고 싶을 때 사용한다.
    'readonly' 속성은 input 필드를 수정할 수 없지만, tab 키로 접근 가능하고, 드래그도 가능하고, Input 안의 텍스트도 복사가 가능하다. 그리고 체크박스를 클릭하는 것처럼 다른 조건이 적용되기 전까지 사용자가 값을 바꾸지 못하게 한다. Javascript는 'readonly'인 값을 제거할 수 있고, input 필드를 편집할 수 있게 하기도 한다.
    Note: form은 readonly인 input 필드는 submit하지만, disabled인 필드는 submit하지 않는다!

     

     

     

     

     

    ✅ 

    그래서 결론은 disabled 속성을 readOnly로 수정하고, input field 스타일도 disabled처럼 변경했다.

    document.getElementById("inputId").readOnly = true;

     

     

     

     

     

     

    참고 사이트

    https://www.w3schools.com/tags/att_input_readonly.asp

     

    HTML input readonly Attribute

    HTML readonly Attribute ❮ HTML tag Example An HTML form with a read-only input field:

       

     

    www.w3schools.com

     

     

     

Designed by Tistory.