Update an item and trigger change (whether disabled or not)

In multiple parts of my code I need to update the value of an item, and in some cases it may have been disabled for user input; but in all cases I want the "change" event to fire, regardless.

I need a function that will take a jQuery expression, and a new value to set any corresponding item(s) to the new value; and then fire the "change" event on them. If the item was disabled, it should remain disabled.

jQuery 1.7.1

Answers 1

  • I'd suggest you to make the <input> readonly instead of disabled.

    Demo

    $("#form").on("change", ".all", function() {
      $("#feedback").append($(this).attr("id") + " changed<br>");
    });
    
    $(".all")
      .val("new value")
      .trigger("change");
    input[readonly] {
      background: #ccc;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
    <div id="form">
      Item1 =
      <input id="item1" class="all">
      <br>Item2 =
      <input id="item2" class="all" readonly />
      <!--                          ^^^^^^^^ -->
      <p id="feedback">
    </div>


Related Articles