admin管理员组

文章数量:1332872

I have an input type select and input type text. What I want is that when I select on "Others" item in the select input, the other input type text will enable, if not it will be disabled. I have a code here, I probably miss something here.

<script type='text/javascript'>

    var others = $('select[name="facility"]').val()
    $().ready(function() {
        if(others == "Others"){
            $('input').each(function() {

                if ($('#disabled_input').attr('disabled')) {
                    $('#disabled_input').removeAttr('disabled');
                }
                else {
                    $('#disabled_input').attr({
                        'disabled': 'disabled'
                    });
                }

            });
        }
        });
    });
</script>

I have an input type select and input type text. What I want is that when I select on "Others" item in the select input, the other input type text will enable, if not it will be disabled. I have a code here, I probably miss something here.

<script type='text/javascript'>

    var others = $('select[name="facility"]').val()
    $().ready(function() {
        if(others == "Others"){
            $('input').each(function() {

                if ($('#disabled_input').attr('disabled')) {
                    $('#disabled_input').removeAttr('disabled');
                }
                else {
                    $('#disabled_input').attr({
                        'disabled': 'disabled'
                    });
                }

            });
        }
        });
    });
</script>
Share Improve this question asked Oct 10, 2013 at 5:50 IkongIkong 2,5704 gold badges40 silver badges61 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 6

Use onchange event to get the value of select and i assume disabled_input id is assigned to only one input field then there is no sense to loop through all the inputs

<script type='text/javascript'>
$(document).ready(function() {
$('#disabled_input').attr('disabled','disabled');        
$('select[name="facility"]').on('change',function(){
var  others = $(this).val();
    if(others == "Others"){           
    $('#disabled_input').removeAttr('disabled');          
     }else{
     $('#disabled_input').attr('disabled','disabled'); 
    }  

  });
});
</script>

See demo here

I don't think there is any need of each here. For every iteration it will check if ($('#disabled_input').attr('disabled')) which u can directly check

var others = $('select[name="facility"]').val();
 $(document).ready(function () {//missing document
     if (others == "Others") {
//no need of each here
         if ($('#disabled_input').attr('disabled')) {
         $('#disabled_input').removeAttr('disabled');
         } 
         else {
         $('#disabled_input').attr({'disabled': 'disabled'});  
         }
     }
 });

本文标签: javascriptJQuery enabledisable input when right select value selectedStack Overflow