如何基于单选按钮切换启用/禁用输入字段

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

本文关键字:输入 字段 启用 何基于 单选按钮      更新时间:2023-12-18

我有一组单选按钮,带有lase选项"其他"和一个输入field type text。默认情况下,输入字段被禁用,如果您单击"其他"单选按钮,则该字段将被启用。如果单选按钮上的选择发生更改,如何禁用输入字段?

这是我的代码:

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

如果您更改收音机选择,此代码不会禁用输入字段。

更新1我正在尝试这个:

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

但如果您更改单选按钮,则不会将输入设置为禁用。

你可以这样做

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

更改:

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

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

试试这个,这里的输入框将切换,即启用/禁用

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

解决方案可以是:

  • change侦听器添加到单选按钮组
  • 当收音机发生变化时,检查其值
  • 如果值为"other",请启用输入字段

工作示例: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);
});