jquery를 사용하여 텍스트 상자를 비활성화 하시겠습니까?


103

이름이 같고 값이 다른 세 개의 라디오 버튼이 있습니다. 세 번째 라디오 버튼을 클릭하면 확인란과 텍스트 상자가 비활성화되지만 다른 두 라디오 버튼을 선택하면 표시되어야합니다 .Jquery에서 도움이 필요합니다. 감사합니다. 전진....

<form name="checkuserradio">
    <input type="radio" value="1" name="userradiobtn" id="userradiobtn"/> 
    <input type="radio" value="2" name="userradiobtn" id="userradiobtn"/>
    <input type="radio" value="3" name="userradiobtn" id="userradiobtn"/>
    <input type="checkbox" value="4" name="chkbox" />
    <input type="text" name="usertxtbox" id="usertxtbox" />
</form>

3
동일한 ID를 제거해야합니다. names는 동일 할 수 있지만 ids는 고유해야합니다.
Eric

답변:


208

HTML

<span id="radiobutt">
  <input type="radio" name="rad1" value="1" />
  <input type="radio" name="rad1" value="2" />
  <input type="radio" name="rad1" value="3" />
</span>
<div>
  <input type="text" id="textbox1" />
  <input type="checkbox" id="checkbox1" />
</div>

자바 스크립트

  $("#radiobutt input[type=radio]").each(function(i){
    $(this).click(function () {
        if(i==2) { //3rd radiobutton
            $("#textbox1").attr("disabled", "disabled"); 
            $("#checkbox1").attr("disabled", "disabled"); 
        }
        else {
            $("#textbox1").removeAttr("disabled"); 
            $("#checkbox1").removeAttr("disabled"); 
        }
      });

  });

@vinothkumar : Matt의 대답이 더 효율적입니다. 저를별로 좋지 않은 예로 생각하십시오.
okw

여기서 i 값을 정의 할 수 있습니다.
svk

@vinothkumar ifunction(i)JQuery의 each(). i==2세 번째 라디오 버튼에 액세스하는 데 사용됩니다. 내 코드를 참조하십시오.
okw

오래된 브라우저에 대한 자비?
sarepta

6
<span id="radiobutt">-RadioHead의 사촌?
Icemanind 2014-08-20

27

실제로 필요하지는 않지만 함수 호출을 더 빠르게 만드는 okw의 코드를 약간 개선했습니다 (함수 호출 외부로 조건부를 이동하기 때문입니다).

$("#radiobutt input[type=radio]").each(function(i) {
    if (i == 2) { //3rd radiobutton
        $(this).click(function () {
            $("#textbox1").attr("disabled", "disabled");
            $("#checkbox1").attr("disabled", "disabled");
        });
    } else {
        $(this).click(function () {
            $("#textbox1").removeAttr("disabled");
            $("#checkbox1").removeAttr("disabled");
        });
    }
});

22

이 스레드는 약간 오래되었지만 정보를 업데이트해야합니다.

http://api.jquery.com/attr/

양식 요소의 선택, 선택 또는 비활성화 상태와 같은 DOM 속성을 검색하고 변경하려면 .prop () 메서드를 사용합니다.

$("#radiobutt input[type=radio]").each(function(i){
$(this).click(function () {
    if(i==2) { //3rd radiobutton
        $("#textbox1").prop("disabled", true); 
        $("#checkbox1").prop("disabled", true); 
    }
    else {
        $("#textbox1").prop("disabled", false); 
        $("#checkbox1").prop("disabled", false);
    }
  });
});

3
+1하지만 removeProp장애인 시설에는 사용할 수 없습니다 . jQuery 문서는 prop("disabled", false);대신 사용한다고 말합니다 . api.jquery.com/prop/#prop-propertyName-value
Lee Grissom

1
prop ()을 사용하는 것이 훨씬 더 좋은 방법입니다. 확인란에 attr ()을 사용하는 데 몇 가지 문제가 있습니다. 처음에는 확인이 두 번째로 응답이 없습니다. 따라서 prop ()을 사용하십시오. 나에게서 +1
brandelizer

11

이러한 솔루션 중 일부가 .each ()를 사용하는 이유를 잘 모르겠습니다. 필요하지 않습니다.

다음은 세 번째 확인란을 클릭하면 비활성화되고 그렇지 않으면 비활성화 된 속성을 제거하는 작동 코드입니다.

참고 : 확인란에 ID를 추가했습니다. 또한 ID는 문서에서 고유해야하므로 라디오 버튼에서 ID를 제거하거나 고유하게 만드십시오.

$("input:radio[name='userradiobtn']").click(function() {
    var isDisabled = $(this).is(":checked") && $(this).val() == "3";
    $("#chkbox").attr("disabled", isDisabled);
    $("#usertxtbox").attr("disabled", isDisabled);
});

1
@ScottE : each()세 번째 라디오 버튼을 얻고 싶기 때문에 사용되었습니다. 우리도 사용할 수 $("input[type=radio]:eq(2)")있습니다. 귀하의 방법은 값으로 라디오 버튼을 식별하며 물론 유효합니다. :)
okw

사용자가 먼저 체크 박스를 선택하고 텍스트 상자에 텍스트를 입력 한 다음 라디오 버튼을 선택하면 체크 된 체크 박스를 선택 취소하고 텍스트 상자를 지워야하는 경우 어떻게해야하나요? anewbie ... 미리 감사드립니다 ..
svk

@vinothkumar-이 요구 사항을 염두에두고 위와 같이 js를 설정하지 않았을 것입니다.하지만이 경우 요소가 비활성화되어 있는지 확인하고 I에서 $ ( "# usertxtbox"). val ( "")을 호출합니다. 것
ScottE

8

나는 오래된 질문에 대답하는 것이 좋은 습관이 아니라는 것을 알고 있지만 나중에 질문을 볼 사람들을 위해이 대답을 넣었습니다.

이제 JQuery에서 상태를 변경하는 가장 좋은 방법은

$("#input").prop('disabled', true); 
$("#input").prop('disabled', false);

전체 그림은이 링크를 확인하십시오. jQuery로 입력을 비활성화 / 활성화 하시겠습니까?


Jquery 공식 웹 사이트에 따르면 소품은 갈 길입니다. +1
Moiz Tankiwala 2014

2

조금 다르게했을 텐데

 <input type="radio" value="1" name="userradiobtn" id="userradiobtn" />   
 <input type="radio" value="2" name="userradiobtn" id="userradiobtn" />    
 <input type="radio" value="3" name="userradiobtn" id="userradiobtn" class="disablebox"/>   
 <input type="checkbox" value="4" name="chkbox" id="chkbox" class="showbox"/>    
 <input type="text" name="usertxtbox" id="usertxtbox" class="showbox" />   

통지 클래스 속성

 $(document).ready(function() {      
    $('.disablebox').click(function() {
        $('.showbox').attr("disabled", true);           
    });
});

이렇게하면 자바 스크립트 변경에 대해 걱정할 필요가없는 라디오 버튼을 더 추가해야합니다.


0

"클릭"이벤트를 여러 라디오 버튼에 바인딩하고, 클릭 한 라디오 버튼의 값을 읽고, 값에 따라 확인란 및 / 또는 텍스트 상자를 비활성화 / 활성화하고 싶을 것 같습니다.

function enableInput(class){
    $('.' + class + ':input').attr('disabled', false);
}

function disableInput(class){
    $('.' + class + ':input').attr('disabled', true);
}

$(document).ready(function(){
    $(".changeBoxes").click(function(event){
        var value = $(this).val();
        if(value == 'x'){
            enableInput('foo'); //with class foo
            enableInput('bar'); //with class bar
        }else{
            disableInput('foo'); //with class foo
            disableInput('bar'); //with class bar
        }
    });
});

제공된 HTML을 사용하여이 작업을 수행하지는 않았지만 상당히 쉽습니다.
Niels Bom

0

파티에 너무 늦어서 미안하지만 여기에 개선의 여지가 있습니다. "텍스트 상자 비활성화"에 관한 것이 아니라 radionbox 선택 및 코드 단순화에 관한 것이기 때문에 나중에 변경하기 위해 좀 더 미래의 증거가됩니다.

우선 .each ()를 사용하지 말고 색인을 사용하여 특정 라디오 버튼을 가리켜서는 안됩니다. 동적 라디오 버튼 세트로 작업하거나 나중에 일부 라디오 버튼을 추가 또는 제거하면 코드가 잘못된 버튼에 반응합니다!

다음으로, OP를 만들었을 때의 경우는 아닐 것입니다. click ... http : //api.jquery 대신 .on ( 'click', function () {...})을 사용하는 것을 선호합니다 . com / on /

무엇보다도 코드는 이름을 기반으로 라디오 버튼을 선택하여 더 간단하고 미래를 보장 할 수 있습니다 (하지만 이미 게시물에 표시됨).

그래서 다음 코드로 끝났습니다.

HTML (okw 코드 기반)

<span id="radiobutt">
    <input type="radio" name="rad1" value="1" />
    <input type="radio" name="rad1" value="2" />
    <input type="radio" name="rad1" value="3" />
</span>
<div>
    <input type="text" id="textbox1" />
    <input type="checkbox" id="checkbox1" />
</div>

JS 코드

$("[name='rad1']").on('click', function() {
    var disable = $(this).val() === "2";
    $("#textbox1").prop("disabled", disable); 
    $("#checkbox1").prop("disabled", disable); 
});

0

MVC 4 @ Html.CheckBox 일반적으로 사람들은 mvc 확인란의 선택 및 선택 취소에 대한 조치를 원합니다.

<div class="editor-field">
    @Html.CheckBoxFor(model => model.IsAll, new { id = "cbAllEmp" })
</div>

변경하려는 컨트롤에 대한 ID를 정의하고 자바 스크립트에서 다음을 수행 할 수 있습니다.

<script type="text/javascript">
    $(function () {
        $("#cbAllEmp").click("", function () {
            if ($("#cbAllEmp").prop("checked") == true) {
                    $("#txtEmpId").hide();
                    $("#lblEmpId").hide();
                }
                else {
                    $("#txtEmpId").show();
                    $("#txtEmpId").val("");
                    $("#lblEmpId").show();
             }
        });
    });

다음과 같이 속성을 변경할 수도 있습니다.

$("#txtEmpId").prop("disabled", true); 
$("#txtEmpId").prop("readonly", true); 

0
$(document).ready(function () {
   $("#txt1").attr("onfocus", "blur()");
});


0

라디오 버튼 값을 가져 와서 각각 3이면 비활성화 checkbox and textbox됩니다.

$("#radiobutt input[type=radio]").click(function () {
    $(this).each(function(index){
    //console.log($(this).val());
        if($(this).val()==3) { //get radio buttons value and matched if 3 then disabled.
            $("#textbox_field").attr("disabled", "disabled"); 
            $("#checkbox_field").attr("disabled", "disabled"); 
        }
        else {
            $("#textbox_field").removeAttr("disabled"); 
            $("#checkbox_field").removeAttr("disabled"); 
        }
      });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<span id="radiobutt">
  <input type="radio" name="groupname" value="1" />
  <input type="radio" name="groupname" value="2" />
  <input type="radio" name="groupname" value="3" />
</span>
<div>
  <input type="text" id="textbox_field" />
  <input type="checkbox" id="checkbox_field" />
</div>

당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.