Hook paste event to hidden textarea - javascript

I want to hook paste event for <input type="text"> and force this text to be pasted into hidden textarea (then I want to parse textarea's text and perform 'paste data from excel to gridview' action). Something like:
$('#input1').bind('paste', function(e) {
// code do paste text to textarea instead of originally targeted input
});
What cross-browser code should I write instead of comments?
Thanks.

There is this hacky solution that fires a focus event on a textarea when Ctrl and V keys or Shift and Insert keys are down. [Yes, it doesn't work for contextmenu -> past]
$(document).ready(function(){
var activeOnPaste = null;
$('#input1').keydown(function(e){
var code = e.which || e.keyCode;
if((e.ctrlKey && code == 86) || (e.shiftKey && code == 45)){
activeOnPaste = $(this);
$('#textarea').val('').focus();
}
});
$('#textarea').keyup(function(){
if(activeOnPaste != null){
$(activeOnPaste).focus();
activeOnPaste = null;
}
});
});
The code lets the pointer focus on a textarea when Ctrl and V keys are down. At that moment no text is pasted, it's pasted after this keydown function is fired so the pasted text is shown in the textarea. After that, on keyup on that textarea, #input1 will be focused.
While typing this, I see that there may be a solution for both keyboard pasting and mouse pasting, using ranges. I'll try something with that too...

You should bind a function to your input-fields onChange() event and copy its content everytime this function is called and process the data afterwards. If you are specifically interested in "pasted" content (I do not know what you are trying to do there, but generally it is a sign of bad concept to be in a situation where pasted content has to be treated additionally) you can try implementing a counter that checks the input speed (eg more than xx characters per second -> PASTE-Eventcall)

Related

How to traverse the input field in the Google search result page and auto focus on it?

I want to set a shortcut to focus on the input field in the Google search result page, instead of using mouseover or mousemove Event.
How to traverse all the elements in a page to get the input field to execute focus() by using Javascript.
document.addEventListener('keydown',function(event){
var keynum;
if(window.event) // IE
{
keynum = event.keyCode;
}
else if(event.which) // Netscape/Firefox/Opera
{
keynum = event.which;
}
console.log(event.keyCode)
if(keynum==79&&event.altKey){
//get the input element in a page and execute focus()
}
});
First of all, to get the search bar element, we need to use the querySelector. After that, we need to focus on the input. Even after this, we will not see the automatic suggestions that google gives us. So, we also need to stimulate the click event. The below code will do the work -
let searchBar = document.querySelector("input[type=text]");
searchBar.focus();
searchbar.click();

Safari issue with text inputs, text is selected as user enters it causing text to be lost

I have the following input element on my page:
<input class="input" name="custom_fields[new]" placeholder="Enter placeholder" type="text">
I have a Twitter Flight event listener on this element that looks like this:
this.on('keyup', {
inputsSelector: this.updateViewInputs
});
Which triggers this method:
this.updateViewInputs = function(ev) {
var isDeletionKeycode = (ev.keyCode == 8 || ev.keyCode == 46);
// Remove field is user is trying to delete it
if (isDeletionKeycode && this.shouldDeleteInput(ev.target.value, this.select('inputsSelector').length)) {
$(ev.target.parentNode).remove();
}
// Add another field dynamically
if (this.select('lastInputsSelector')[0] && (ev.target == this.select('lastInputSelector')[0]) && !isDeletionKeycode) {
this.select('inputsContainer').append(InputTemplate());
}
// Render fields
that.trigger('uiUpdateInputs', {
inputs: that.collectInputs()
});
}
And finally triggers uiUpdateInputs:
this.after('initialize', function() {
this.on(document, 'uiUpdateInputs', this.updateInputs)
});
this.updateInputs = function(ev, data) {
// Render all inputs provided by user
this.select('inputListSelector').html(InputsTemplate({ inputs: data.inputs }));
}
All of this functionality works as expected on Chrome and Firefox. Users can type into the input and see the page change in 'real time'. Users also get additional fields that they can enter text into and see the page change.
The issue in question arises when using Safari, as a user enters text into the described input field the text in the input field becomes highlighted (selected) and when they enter the next character all the content is replaced with that single character. This results in the user not being able to enter more than 1 or 2 characters before having them all replaced by the next entered character.
I have tried several approaches to fix this problem but none have worked, they include:
Using a setTimeout to delay the code run on the keyup event
Using Selection to try to disable the selection of the text using collapseToEnd.
Using click,focus,blur events to try to remove the selection from the entered text
Triggering a right arrow key event to try to simply move the cursor forward so they user does not delete the selected text
Using setInterval to routinely remove selections made by the window
I am very confused why this is happening and I am wondering if this is a bug in webkit with Flight. I see no issue with the Firefox or Chrome versions of this page. Thanks for any help!
This seems to be an issue with certain versions of Safari. When listening for the keyup function in javascript it will automatically select all of the text in the box and subsequently delete it all when the next key is typed. To prevent this from happening call preventDefault on the event object that is passed to the keyup function.
this.on('keyup', function(e) {
e.preventDefault()
});

Virtual Keyboard with Jquery

I have a div that operates as a button. Once the button is clicked, I want it to simulate the pressing of a key. Elsewhere on Stackoverflow, people have suggested using jQuery.Event("keydown"); but the suggestions all use a .trigger() bound to the button as opposed to .click. So, my example code looks like this:
var press = jQuery.Event("keydown");
press.which = 69; // # The 'e' key code value
press.keyCode = 69;
$('#btn').click( function() {
$('#testInput').focus();
$(this).trigger(press);
console.info(press);
});
I've set up a dummy example at JSFiddle:
http://jsfiddle.net/ruzel/WsAbS/
Eventually, rather than have the keypress fill in a form element, I just want to register the event as a keypress to the document so that a MelonJS game can have it.
UPDATE: It looks like triggering a keypress with anything other than the keyboard is likely to be ignored by the browser for security reasons. For updating a text input, this very nice Jquery plugin will do the trick: http://bililite.com/blog/2011/01/23/improved-sendkeys/
As for anyone who comes here looking for the solution in the MelonJS case, it's best to use MelonJS's me.input object, like so:
$('#btn').mousedown(function() {
me.input.triggerKeyEvent(me.input.KEY.E, true);
});
$('#btn').mouseup(function() {
me.input.triggerKeyEvent(me.input.KEY.E, false);
});
I'm not sure why, but even though this is triggering the event correctly, it doesn't fill the input with the character.
I've modified the code to show that the document is indeed receiving keypress events when we say $(document).trigger(p)
Try it out:
http://jsfiddle.net/WsAbS/3/
var press = jQuery.Event("keydown");
press.which = 69; // # Some key code value
press.keyCode = 69;
press.target = $('#testInput');
$(document).on('keydown', function(event) {
alert(event.keyCode);
});
$('#btn').click( function() {
$(document).trigger(press);
});
I believe this should be good enough for your end goal of a MelonJS game picking up keypresses.
If you want a virtual keyboard (As the title suggests) you can use this one.

How do write a JavaScript function that allows for non-editable textbox?

I need to have an input textbox in which I can click and the cursor starts blinking but the user cannot change any text inside it.
I tried using "readonly" or "disabled" attributes, but they do not allow the cursor to be inside the textbox. So, I was thinking of a solution to implement in JavaScript on a normal textbox. Is there a plugin that already do this? How do I implement this?
EDIT: Thanks for all the answers, but I wanted to make the textarea/input type text as uneditable but selectable at the same time. Pressing Ctrl + A inside the textbox doesn't work. Is it possible to get the changed value and the old value and compare them and then return false if the values are different, but in all other cases return true so that the Ctrl + A, Shift + end, etc. combinations work?
Something like this:
<textarea onkeydown="javascript:return false;"></textarea>
would do the trick. (jsfiddle)
You can also do that at runtime if you want to:
<textarea class="readonly"></textarea>
with
$(".readonly").keydown(function() false);
The onkeydown callback captures keystroke events and cancels them using return false;.
Depending on what you are trying to do, you may want to prevent other kind of events, since it is still possible to change the contents with the mouse, for instance.
Your callback function can accept or cancel events depending of the kind of keystroke. For example, to enable only ctrl-a and ctrl-c (with jQuery):
function keydown(e) {
if(!e.ctrlKey) return false; // Cancel non ctrl-modified keystrokes
if(e.keyCode == 65) return true;// 65 = 'a'
if(e.keyCode == 67) return true;// 67 = 'c'
return false;
}
$(function(){
$("inputSelector").keydown(function(){ return false; });
});
You cannot rely on disabling a <textarea> as a user input, as it's trivial to remove any sort of HTML or javascript disabling with firebug, or other tools. Remember that forms aren't limited to the fields you give them, anyone can submit any data to a page.
Disabled inputs are not submitted with a form anyway, bearing that in mind my advice would be to not use a textarea and just print it out.

keydown event for form or div in html

I am displaying a form inside a div tag as a dialog to enter details.
In this form, I want to handle the ESC key using jQuery.
If any input tags have focus, keydown event will trigger. If the focus is on the form but not on any input tags then it will not trigger keydown event.
Here is my code:
$("#NewTicket").keydown(function(e) {
var unicode = e.keyCode ? e.keyCode : e.charCode
if (unicode == 27)
{
if (confirm("Are you sure you want to cancel?"))
return true
else
return false
}
});
Just add an id,class to the form
<form id="form">
....
and now do this :
$("#NewTicket,#form").keydown(function(e)
{
var unicode=e.keyCode? e.keyCode : e.charCode
if(unicode == 27)
{
if (confirm("Are you sure you want to cancel?"))
return true
else
return false
}
)};
This should work
You can't focus on forms. If you wan't to handle keydown on elements that don't get focus (such as divs or forms) you have to bind it to the document.
Turns out that jQuery automatically adds :focus selector which enables you to find the focused element by using $(':focus')
I believe that if you put your form in an element made focusable using tabIndex, like , or this focusable div is the container element inside the form, then you can bind the keyDown to this div instead. It works cross browser as far as I've tested but I've not seen this solution discussed much, so curious as to anyone's comments about this.
I know this is an old question but someone still might be looking for an answer.
Usually, I do capture key down at global level then forward it to a function and handle it there. For your needs, you can get nodeName. (Tested in FF, Chrome)
$(document).keydown((e)=>{//Capture Key
if(["INPUT","TEXTAREA"].indexOf(e.target.nodeName)!==-1){//If input in focus
console.log("INPUT FOCUSED",e.code,e.keyCode);
if(e.keyCode==27 || e.code=="Escape"){//Capture Escape key
console.log('ESC');
}
}
});

Categories