본문 바로가기
Frontend

[JS/jQuery] 버튼 활성화/비활성화 (+ fieldset)

by unknownomad 2022. 3. 28.

input 태그의 disabled 속성

<input type="button" value="button1"/> <!-- 버튼 활성화 -->
<input type="button" value="button2" disabled/> <!-- 버튼 비활성화 -->
<input type="button" value="button3" disabled="disabled"/> <!-- 버튼 비활성화 -->

버튼 클릭 ➡ 활성화/비활성화

<input type="button" value="activeBtn" onclick="btnActive()"/>
<input type="button" value="disabledBtn" onclick="btnDisabled()"/>

 

1. JS

function btnActive() {
    const target = document.getElementById("btnId");
    target.disabled = false;
]

function btnDisabled() {
    const target = document.getElementById("btnId");
    target.disabled = true;
}

 

2. jQuery

$(function() {
    //버튼 비활성화
    //방법1
    $("#btnId").prop("disabled", true);
    $("#btnId").attr("disabled", "disabled");
    //방법2
    //메서드 체인 방식
    $("#btnId").click(function() {
        alert("before disabled event");
    }).prop("disabled", true);
    
    //버튼활성화
    $("#btnId").prop("disabled", false);
    $("#btnId").removeAttr("disabled");
});

fieldset 안의 버튼 활성화/비활성화

1. fieldset 안의 모든 버튼 비활성화

<fieldset disabled>
    <legend></legend>
    <input type="button" id="btnId1" value="button1"/>
    <input type="button" id="btnId2" value="button2"/>
</fieldset>

 

2. 버튼 클릭 ➡ fieldset 안의 모든 버튼 비활성화

function fieldsetDisabled() {
    const fieldset = document.getElementById("fieldsetId");
    fieldset.disabled = true;
}

 


출처

https://hianna.tistory.com/477

https://zetawiki.com/wiki/JQuery_%EB%B2%84%ED%8A%BC_%EB%B9%84%ED%99%9C%EC%84%B1%ED%99%94

댓글