2

I wanted to find out how a change event is being triggered. I want to determine whether it's triggered using by mouse click, or it's triggered by a key stroke from a keyboard.

Edited:

Ok. Here's what I wish to do. This is simple ajax working that fetches the cities listing on change event of the states. My code is all good and it really does the job.

$('#state').change(function(event) {
    $.ajax({
        url: target,
        type: 'POST',
        data: data,
        success: function(data, textStatus, XMLHttpRequest) {
            $('#cityBox').html( data );
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            alert("error");
        }
    });
});

The problem: Chrome messes with the .change event. It calls the change event when I use the keyboard keys as well. So if I use the arrow key or any other key to change the state, for every key press it will trigger the change event, which I want not to happen.

Expected approaches:

1) If I can make out, how the event is being triggered, maybe I can override chrome's working. But the problem is .which does not work for .change event. It always return undefined.

2) Using an if else. Something like this one, but its certainly not going to work as I know.

$('#state').change(function(event) {
    if(!$('#state').keyup()) {
        $.ajax({
            url: target,
            type: 'POST',
            data: data,
            success: function(data, textStatus, XMLHttpRequest) {
                $('#cityBox').html( data );
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                alert("error");
            }
        });
    }
});

3) Storing the key value to some variable and check if it exists or not. The problem with this working is that, I am unable to set variable this_key when the event is triggered with mouse.

var this_key=0;

$('#state').change().keyup(function(e) {
    var code = (e.keyCode ? e.keyCode : e.which);
    if(code!= 13) { // If not enter key
        this_key=code;
    }
});

$('#state').change(function(event) {
    if(!this_key) {
        setTimeout(function(){
            $.ajax({
                url: target,
                type: 'POST',
                data: data,
                success: function(data, textStatus, XMLHttpRequest)     {
                    $('#cityBox').html( data );
                },
                error: function(XMLHttpRequest, textStatus, errorThrown) {
                    alert("error");
                }
            });
        }, 100);
    }
});
4

1 回答 1

1
<!DOCTYPE html>
<html>
<head>
    <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>

    <input id="inputsource" value="do something :)">
    <div id="log"></div>
    <script>
        $('#inputsource').bind('change keydown mousedown',function(e){
            console.log(e.type);
            $('#log').html(e.type);
        });
    </script>

</body>
</html>
于 2012-04-23T09:53:08.967 回答