Pregunta

I am having trouble enabling and disabling a button based on an if/else statement in jQuery. The problem here is that, when the text input is in focus, the button is immediately enabled. The code seems to be ignoring the parameters in the if statement. Obviously, this is not the app I am trying to make, but I made this bit of code to test a portion of the site that is not working. Any suggestions?

Here is the HTML

<input type="text" id="type_here" />
<input type="button" id="test_button" value="test" disabled/>

Here is the Javascript

$(document).ready(function () {
    $(document).click(function () {
        if ($('#type_here').val !== "") {
            $('#test_button').prop('disabled', false);
        } else {
            $('#test_button').prop('disabled', true);
        }
    }).keyup(function () {
        if ($('#type_here').val !== "") {
            $('#test_button').prop('disabled', false);
        } else {
            $('#test_button').prop('disabled', true);
        }
    });
});
¿Fue útil?

Solución

Try this:-

YOu are using .val instead of .val() .val always will return the function reference not the result of the function. So your statement will always be true.

   $(document).ready(function () {
    $(document).click(function () {
            $('#test_button').prop('disabled', $('#type_here').val() === "");
    }).keyup(function () {
           $('#test_button').prop('disabled', $('#type_here').val() === "");
           });
});

Otros consejos

$('#type_here').on('keyup change',function(){
  if($(this).val().length == 0)
     $('#test_button').prop('disabled', true);
  else
     $('#test_button').prop('disabled', false);
});

This will do same thing. Initially button is disabled and after typing something it'll be enabled.

demo

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top