Pregunta

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

¿Fue útil?

Solución

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

Otros consejos

Use boolean values to disable / enable properties with prop() :

$('#dpd1').on('keyup', function () {
    $('#dpd2').prop('disabled', this.value.length < 1); 
});

FIDDLE

Yeah, click won't work here, you need to implement change handler, then check whether the value is an empty string, and if not, change the disabled property on the other input.

Something like:

$('#dpd1').change(function () {
    $("#dpd2").prop('disabled', $('#dpd1').val() == '');
});
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top