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);
        }
    });
});
有帮助吗?

解决方案

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

其他提示

$('#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

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top