blind to the onbvious blind to the onbvious - 9 months ago 34
jQuery Question

Combining two input events

i am aiming to remove the javascript from the input so i’m writing a bit of jquery

the javascript:

<input type="text" id = "IDthisinput'" class="CLthisinput'" placeholder="First"
onChange = "dosomething();"
onKeyPress = "this.onchange();"
onpaste = "this.onchange();"
oninput = "this.onchange();"
/>
<span id="ReturnedMsg"></span>
<span id="IDActionVal"></span>


the jquery:

$('.CLthisinput').on('keyup', function () {
$('#ReturnedMsg').html(dotuff('#'+this.id,$(this).val()));
$('#IDActionVal').html('#'+this.id + ' ' + 'keyup ' + $(this).val());
});
$('.thisinput').on('paste', function () {
$('#ReturnedMsg').html(dotuff('#'+this.id,$(this).val()));
$('#IDActionVal').html('#'+this.id + ' ' + 'keyup ' + $(this).val());
});


I’m stumped when it comes to shortening the above, which works fine, to something like this:

$('.thisinput').on('keyup', 'paste', function () {
var theaction = event
$('#ReturnedMsg').html(dotuff('#'+this.id,$(this).val()));
$('#IDActionVal').html('#'+this.id + ' ' + theaction + ' ' + $(this).val());
});


How can I get the events to work together?!

Answer Source

Enumerate both events in the same string, separated by space:

$('.thisinput').on('keyup paste', function () {
        var theaction = event
        $('#ReturnedMsg').html(dotuff('#'+this.id,$(this).val()));
        $('#IDActionVal').html('#'+this.id + '  ' + theaction + '  ' + $(this).val());
});

You can’t pass them as separate arguments, because $('.thisinput').on('keyup', 'paste', ...) does something completely different: it fires when a keyup event occurs inside <paste> tag inside .thisinput (and allows <paste> tags to be added dynamically).

You can use event.type to find out the type of the event:

$('.thisinput').on('keyup paste', function () {
        var theaction = event
        $('#ReturnedMsg').html(dotuff('#'+this.id,$(this).val()));
        $('#IDActionVal').html('#'+this.id + '  ' + theaction.type + '  ' + $(this).val());
});

Also, don’t use the global event object (also known as window.event). This is a non-standard extension introduced by Microsoft, it will not work in Firefox. Instead, pass the event as an argument to your callback:

$('.thisinput').on('keyup paste', function (event) {
        var theaction = event
        $('#ReturnedMsg').html(dotuff('#'+this.id,$(this).val()));
        $('#IDActionVal').html('#'+this.id + '  ' + theaction + '  ' + $(this).val());
});

Also, you don’t really need theaction and event to be separate variables:

$('.thisinput').on('keyup paste', function (theaction) {
        $('#ReturnedMsg').html(dotuff('#'+this.id,$(this).val()));
        $('#IDActionVal').html('#'+this.id + '  ' + theaction.type + '  ' + $(this).val());
});