简体   繁体   中英

How to toggle enable/disable input field based on radio button

I have a group of radio buttons with the lase option "Other" and an input field type text . By default the input field is disabled, if you click on "Other" radio button the field is then enabled. How do I disable the input field if the select on radio button is changed?

This is my code:

$(document).ready(function(){
     $("#text-inputt").prop('disabled', true)
 });
$("#lastt").click(function(){ $("#text-inputt").prop('disabled', false/true)});

this code is not disabling the input field if you change the radio select.

UPDATE 1 I'm trying this:

 $(document).ready(function(){
     $("#text-inputt").prop('disabled', true);
 });
$("#lastt").click(function(){ 
if($(this).is(':checked')) {
      $("#text-inputt").prop("disabled", false);
  }  else {
      $("#text-inputt").prop("disabled", true);
  }  
});

But is not setting the input to disable if you change the radio button.

change :

$(document).ready(function(){
$("#text-inputt").prop('disabled', true)
});
$("#lastt").click(function(){ $("#text-inputt").prop('disabled', false/true)});

to

 $(document).ready(function(){
 $("#text-inputt").prop('disabled', true)
 });
 $("#lastt").click(function(){
 if($(this).val=='Other')
 {
 $("#text-inputt").prop('disabled', false)
 }
 else
 {
  $("#text-inputt").prop('disabled', true)
 }
 });

Try this , Here Input box will toggle ie Enable/Disbale

$("#radioBtn").change(function(){
  $("#inputBox").attr("disabled", ! $(this).is(':checked'));    
});

You can do it like this

 $(document).ready(function(){
    $("#text-inputt").prop('disabled', true);
    $('input[type=radio]').click(function(){
        if($(this).prop('id') == "lastt"){
         $("#text-inputt").prop("disabled", false);
      }else{
        $("#text-inputt").prop("disabled", true);
      }

    });
 });

A solution could be:

  • add a change listener to your radio button group
  • When a radio changes, check its value
  • if the value is 'other', enable the input field.

Working example: https://jsfiddle.net/3afjqe7j/1/

var $input = $('#text-inputt');

$("input[name=my-radios]").on('change', function() {
    var disabled = $(this).val() !== 'other';
    $input.prop('disabled', disabled);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM