Search code examples
phpjquerymysqlcascadingdropdown

Jquery live('change', function() wont trigger drop down


Anyone can see anything wrong with this code? It is connected to a php function that echos Json data. I am running Jquery 1.9.1. I belive the problem is at the end of the Jquery script, but I can´t find any solution...

var formObject = {
   run : function(obj) {
        if (obj.val() === '') {
       obj.nextAll('.update').html('<option value="">----</option>').attr('disabled', true);
   } else {
       var id = obj.attr('id');
       var v = obj.val();
       jQuery.getJSON('func/blankett_func.php', { id : id, value : v }, function(data) {
            if (!data.error) {
                obj.next('.update').html(data.list).removeAttr('disabled');
            } else {
                obj.nextAll('.update').html('<option value="">----</option>').attr('disabled', true);
            }
        });
    }
}
  };
$(function() {

    $('.update').live('change', function() {
        formObject.run($(this));
    });

});

The Php function:

$id = $_GET['id'];
$value = $_GET['value'];

try {

    $objDb = new PDO('mysql:host=localhost;dbname=blankett', 'root', 'root');
    $objDb->exec('SET CHARACTER SET utf8');

    $sql = "SELECT * 
            FROM `region`
            WHERE `master_id` = ?";
    $statement = $objDb->prepare($sql);
    $statement->execute(array($value));
    $list = $statement->fetchAll(PDO::FETCH_ASSOC);

    if (!empty($list)) {

        $out = array('<option value="">Select one</option>');

        foreach($list as $row) {
            $out[] = '<option value="'.$row['id'].'">'.$row['region'].'</option>';
        }

        echo json_encode(array('error' => false, 'list' => implode('', $out)));

    } else {
        echo json_encode(array('error' => true));
    }

} catch(PDOException $e) {
    echo json_encode(array('error' => true));
}

    } else {
echo json_encode(array('error' => true));
  }

Solution

  • The problem with the original code was in the .live of the javascript, it should be changed to .on

    The reason for it not triggering was that jQuery changed the API. http://api.jquery.com/on/

    The new jQuery script:

    var formObject = {
    run : function(obj) {
        if (obj.val() === '') {
            obj.nextAll('.update').html('<option value="">----</option>').attr('disabled', true);
        } else {
            var id = obj.attr('id');
            var v = obj.val();
            jQuery.getJSON('func/blankett_func.php', { id : id, value : v }, function(data) {
                if (!data.error) {
                    obj.next('.update').html(data.list).removeAttr('disabled');
                } else {
                    obj.nextAll('.update').html('<option value="">----</option>').attr('disabled', true);
                }
            });
        }
    }
    };
    $(function() {
    
    $('.update').on('change', function() {
        formObject.run($(this));
    });
    
    });