How to handle programmatically changing the state of an input element in javascript

I'm having a weird problem. While the user changing the checkbox input element on the form creates adequate programmatic changes for events, it doesn't. How do I face this challenge? The following code:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <title></title>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.js"></script>
  <script type="text/javascript">
    jQuery(document).ready(
      function() {        
        jQuery("#cb").change(
          function() {
            alert("Changed!"); 
            return true;
          }
        );
        jQuery("#b").click(
          function() {
            var newState = !jQuery("#cb").attr('checked');
            jQuery("#cb").attr('checked', newState);
          });
      });
  </script>
</head>
<body>
  <form action="#">
    <p>
      <input type="button" id="b" />
      <input type="checkbox" id="cb" />
    </p>
  </form>
</body>
</html>

      

Update I have no control over the changes of the elements, I just need to handle them. This is the accepted code that I write.

+1


source to share


4 answers


It is not possible to track the state of an object in javascript, as it can in Objective-C (KVO). Can't use DOM functions - The DOM doesn't fire events on every property change - instead, it fires events only for certain user actions: mouse clicks, keystrokes, or the page life cycle and their derivatives.



One could achieve this just by firing every time it modifies any property. Of course this can be encapsulated in the function AnthonyWJones mentioned.

+1


source


use a trigger function to fire a click event on the checkbox. You won't need to grab the existing state as the checkbox will just be toggled with a click.



jQuery("#cb").trigger('click');

      

+4


source


In this case, you don't have to code the logic in the event handler function itself. You should put any such logic in a separate function. Likewise, you shouldn't place code that manipulates the values ​​of checkboxes programmatically directly in other sequences of code, but abstracts it into another function: -

jQuery(document).ready(
  function() {

    jQuery("#cb").change(
      function() {
        changeLogicForcb.call(this);
         return true; 
     }
    );

    jQuery("#b").click(
      function() {
         togglecb();            
      });

    function changeLogicForcb()
    {
         //something actually sensible here
         alert("changed!");
    }

    function togglecb()
    {
        var cb = jQuery("#cb");
        var newState = !cb.attr('checked');
        cb.attr('checked', newState);
        changeLogicForcb.call(cb.get(0));         
    }  

  });

      

+1


source


The main jQuery.val () method does not fire the change event. If you're serving your own copy of jQuery, you can change the library method, but that probably wouldn't make sense. Instead, you can add your own set of values ​​that uses .val () and also fires a change event by something on the following lines:

jQuery.fn.xVal = (function() {
    return function(value) {
        // Use core functionality
        result = this.val.apply(this, arguments);
        // trigger change event
        if (result instanceof jQuery) {
              result.change();
        }
        return result;
    };
})();

      

+1


source







All Articles