views:

30

answers:

1

How can I can I get the correct current value in the click event to call via a trigger?

Html:

<input type="checkbox" id="mycheck" />
<br />
<span id="actual-value-inevent"></span>
<br />
<span id="actual-value"></span>
<br />
<button id="view-value">view value</button>
<br />
<button id="call-trigger">call trigger</button>
<br />
<button id="call-trigger-handler">call trigger handler</button>

Javascript:

$('#mycheck').bind('click', function(ev) {
    $('#actual-value-inevent').html('value in event : ' + $(this).is(':checked'));
});

$('#view-value').bind('click', function(ev) {
    $('#actual-value').html('value view : ' + $('#mycheck').is(':checked'));
});

$('#call-trigger').bind('click', function(ev) {
    $('#mycheck').trigger('click');
    $('#actual-value').html('value post trigger: ' + $('#mycheck').is(':checked'));
});

$('#call-trigger-handler').bind('click', function(ev) {

    $('#mycheck')[0].checked = !$( "input" )[ 0 ].checked;
    $('#mycheck').triggerHandler('click');

    $('#actual-value').html('value post triggerHandler: ' + $('#mycheck').is(':checked'));

});

If I call the "trigger ('click')", in the event the current value of the checkbox is pre-click.

On this blog I find a solution, but I need to solve the problem in the function of the event, not to call the trigger.

example
example with solution

possible solution by overriding the trigger method:

​(function($){

    var triggerOverwrite = $.fn.trigger;
    $.fn.trigger = function (eventType, extraParameters) {

        var stringEvent = '';
        if (typeof eventType == 'string')
            stringEvent = eventType;
        else 
            stringEvent = eventType.type;

        if (this.get(0).tagName.toLowerCase() == 'input' 
            && stringEvent == 'click' && $(this).attr('type') == 'checkbox')
        {
            $(this)[0].checked = !$(this)[0].checked;
            return $(this).triggerHandler(stringEvent, extraParameters);
        }

        return triggerOverwrite.apply(this, arguments);

    };


})(jQuery);​

run

A: 

The click event applied to the check box is run before the click makes any changes.

So in your check box click event do the following:

$('#mycheck').bind('click', function(ev) {
    $('#actual-value-inevent').html('value in event : ' + !$(this).is(':checked'));
});
Nalum
if I do this when calling a normal event, I have the wrong value
andres descalzo
my bad, didn't check that. but why go to the trouble of overwriting the trigger method when your second example works fine? Why does it have to happen in the event function?
Nalum
for me, this would be a more normal behavior of the method trigger. I might be wrong
andres descalzo