简体   繁体   中英

Easy modification to jQuery code to make use of more than one textbox

How to change the following code to make use of all my 4 textboxes with id extra1, extra2,persons and tables?

$(document).ready(function () {
  $('#extra1').blur(function () {
        if ($.trim(this.value) == "") {
          $('#btnUpdate').attr("disabled", true);
        }
      else {
            $('#btnUpdate').removeAttr("disabled");
      }
    });
});
  $('#extra1').blur(function () {

  $('#extra1, #extra2, #persons, #tables').blur(function () {

The code modification would be:

$(document).ready(function () {
  $('#extra1, #extra2, #persons, #tables').blur(function () {
        if ($.trim(this.value) == "") {
          $('#btnUpdate').attr("disabled", true);
        }
      else {
            $('#btnUpdate').removeAttr("disabled");
      }
    });
});

But, why not give all of them a class, and use that class as the selector? That way, you can easily add elements later without changing your Javascript.

Use jQuery delegate which will bind only one event handler but will act only on the element which triggers the event . Try this

Wokring demo

$(document).ready(function () {
  $('formSelector').delegate('input[type=text]', 'blur', function () {
      if ($.trim(this.value) == "") {
          $('#btnUpdate').attr("disabled", true);
      }
      else {
            $('#btnUpdate').removeAttr("disabled");
      }
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM