Search code examples
jqueryhtmlformsdisabled-input

how to remove 'disabled' from input if previous input has value


I've been trying some experimentation with jQuery, basically it's not working, this is my HTML:

<input class="span4" value="" id="dpd1" type="text"> <!-- Input that needs value -->
<input class="span4" value="" id="dpd2" type="text" disabled> <!-- Input which needs 'enabled' -->

and here's what I'm trying with jquery:

$('#dpd2').click( function () {
    var value = $('#dpd1').val();
    if( value.length > 0 ){
    $("#dpd2").prop('disabled', disabled); }
    });

probably shouldn't be trying to have all this happen on click, but I haven't really done anything like this in jQuery before, so not sure what way is best for this type of situation.

Any help is appreciated.

EDIT: I picked the answer which best highlighted the shortest and effective way for me to achieve the outcome I wanted. But there are some other great answers there too! Thanks!!


Solution

  • You may want to do it in the blur of first textbox,

    $('#dpd1').blur(function () {
        $("#dpd2").prop('disabled', !$.trim($('#dpd1').val()).length);
    });
    

    Demo

    prop takes a boolean. And when you set your textbox to disabled initially you can no longer click on it. hence use blur to perform the action once you focus out of the first textbox.Use $.trim() to remove the whitespaces from ends of the textbox value