Reputation: 4607
I have the following jquery binding to listen for paste action in certain text input elements. Is there a way inside of the function to get a reference to the actual element that triggered the event? My goal is to clear out the text in the input if anything is pasted inside out it, but 'this' doesn't seem to be correct.
Edit, the code has been updated:
$(window).on("load", function() {
$('.watchable').bind("paste", function() {
alert('called!');
$(this).val('');
});
});
I am using JQuery 1.11.3. I see the alert, but the text is not cleared out.
Here is a jsFiddle demo. Paste any text into either of the 2 text fields, the alert displays, but the text in the text field is not cleared out.
https://jsfiddle.net/8bep1Lxh/
Upvotes: 0
Views: 347
Reputation: 1209
Update
If you'd like to always clear the field when pasting is attempted, then see the following updated examples:
My Fiddle - https://jsfiddle.net/8v08n4vx/
Your Fiddle - https://jsfiddle.net/jmap4jhy/
They prevent the default paste event unless the field is already empty.
If you'd like to prevent it altogether, simply remove the if ($(this).val() !== ""){
statement.
My Fiddle - https://jsfiddle.net/7Lsr7j78/
Your Fiddle -https://jsfiddle.net/pzb9s7s4/
(However, you should think about the possible negative impact manipulating the ubiquitious paste event may have on user experience)
$('.watchable').on('paste', function (e) {
//if field is not empty
if ($(this).val() !== "") {
// prevent default paste event
e.preventDefault();
// and clear field
$(this).val('');
}
});
Seeing as you're using a version of jQuery greater than 1.7, you should use on
instead of bind
.
My Fiddle - https://jsfiddle.net/ae8ufz7y/
Your Updated Fiddle - https://jsfiddle.net/83263j4e/
You simply need to add the following JavaScript:
$('.watchable').on('paste', function () {
// on paste, clear input
$(this).val('');
});
Here is the jQuery documentation on the on
method:
http://api.jquery.com/on/
Upvotes: 1
Reputation: 1
Better I think is to disable the paste event instead to clear out the text
$('.some-el').on('paste', function() {
return false;
});
On paste event the value of input can't be captured(and modified) because the input change asynchronously with 'paste' event.
Just the next event can capture the value of input after paste event
$('.some-el').on('input', function() {});
Upvotes: 0