How it fails if the text field unexpectedly has values

Can someone help me turn off my button if mine texboxsuddenly filled in the text without pressing the text field to enter anything.

My problem is that my code is not working. Does anyone know how to do this.

<form method="post">
<input type="text" name="name1" id="name1" class="number" />
<input type="text" name="name2" id="name2" class="number" />
<input type="submit" name="send" id="send" class="hey" value="one" disabled />
</form>

script code:

<script>
$(document).ready(function () {
  $('.number').blur(function () {
        if ($.trim(this.value) == "") {
          $('#send').attr("disabled", true);
        }
      else {
            $('#send').removeAttr("disabled");
      }
    });
});
</script>
+3
source share
4 answers

You can use a combination of input, blur events and key events:

$('.number').on('keyup blur input', function () {
    $('#send').prop("disabled", !$.trim(this.value));
});

Demo: http://jsfiddle.net/pb9vw/

+3
source
$('.number').keyup(function () {
    if ($.trim(this.value) == "") {
      $('#send').addAttr('disabled');
    }
  else {
        $('#send').removeAttr('disabled');
  }
});
+1
source

keyup blur prop() attr() . , ..

Live Demo

$('.number').keyup(function () {
    if ($.trim(this.value) == "") {
      $('#send').prop("disabled", true);
    }
  else {
        $('#send').prop("disabled", false);
  }
});

As in jQuery 1.6, the .attr () method returns undefined for attributes that have not been set. To retrieve and modify DOM properties, such as the checked, selected, or disabled state of form elements, use the .prop () link .

0
source

If you want the button to turn on only when filling in two text fields, you can:

function doCheck() {
    var allFilled = true;
    $('input[type=text]').each(function () {
        if ($(this).val() == '') {
            allFilled = false;
            return false;
        }
    });
    $('input[type=submit]').prop('disabled', !allFilled);
}

$(document).ready(function () {
    $('input[type=text]').keyup(doCheck);
});

Demo Screenshot

0
source

All Articles