programing

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

nasanasas 2020. 8. 21. 07:51
반응형

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


이름이 같고 값이 다른 세 개의 라디오 버튼이 있습니다. 세 번째 라디오 버튼을 클릭하면 확인란과 텍스트 상자가 비활성화되지만 다른 두 라디오 버튼을 선택하면 표시되어야합니다 .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>

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"); 
        }
      });

  });

실제로 필요하지는 않지만 함수 호출을 더 빠르게 만드는 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");
        });
    }
});

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

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);
    }
  });
});

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

Here's some working code that disables if the 3rd checkbox is clicked, otherwise is removes the disabled attribute.

Note: I added an id to the checkbox. Also, remember that ids must be unique in your document, so either remove the ids on the radiobuttons, or make them unique

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

I know it is not a good habit to answer an old question but I'm putting this answer for people who would see the question afterwards.

The best way to change the state in JQuery now is through

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

Please check this link for full illustration. Disable/enable an input with jQuery?


I would've done it slightly different

 <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" />   

Notice class attribute

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

This way should you need to add more radio buttons you don't need to worry about changing the javascript


I'm guessing you probably want to bind a "click" event to a number of radio buttons, read the value of the clicked radiobutton and depending on the value, disable/enable a checkbox and or textbox.

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
        }
    });
});

Sorry for being so late at the party, but I see some room for improvement here. Not concerning "disable textbox", but to the radionbox selection and code simplification, making it a bit more future proof, for later changes.

First of all, you shouldn't use .each() and use the index to point out a specific radio button. If you work with a dynamic set of radio buttons or if you add or remove some radio buttons afterwards, then your code will react on the wrong button!

Next, but that wasn't probably the case when the OP was made, I prefer to use .on('click', function(){...}) instead of click... http://api.jquery.com/on/

Lst but not least, also the code could be made more simple and future proof by selecting the radio button based on it's name (but that appeared already in a post).

So I ended up with the following code.

HTML (based on code of o.k.w)

<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-code

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

MVC 4 @Html.CheckBoxFor generally people want to action on check and uncheck of mvc checkbox.

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

you can define id for the controls you want to change and in javascript do the folowing

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

you can also change the property like

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

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

$(document).ready(function () {
  $("#txt1").attr("onfocus", "blur()");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<input id="txt1">


get radio buttons value and matches with each if it is 3 then disabled 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>

참고URL : https://stackoverflow.com/questions/1648901/disable-textbox-using-jquery

반응형