I'm trying to pass an keydown event from one textbox to another. What I mean with this is that if you, for example, press the 'a' key, some code should simulate that key as being pressed in the second textbox.
I do not want to just copy the value of the first textbox into the second - it should be on a per-key basis so to say. Suppose the first textbox contains abc and the second textbox is empty, when you then press the 'd' key in textbox 1, textbox 2 should only contain d.
What I already tried is (http://jsfiddle.net/E5qyr/1/):
$('#t1').keydown(function(e) {
$('#t2').keydown(e);
});
But this does not work (I guess I'm thinking too simple). I know I could append the character pressed by looking at e.keyCode, but also 'backspace' etc. has to be working.
Does anybody have an idea to pass a keydown event from one textbox to another?
Textarea elements don't have listeners automatically installed to them, so triggering a 'keydown' event for the #t2 will not show a response. What you want is to just add the text you get from the #t1 keydown event (of which you are listening) and append it to your #t2.
UPDATED with support for backspace. Other codes found here.
Example:
$('#t1').keydown(function(e) {
if (e.which == 8) { //Backspace
this.text(this.val().substr(0, this.val().length - 1));
} else {
$('#t2').append($('#t1').val());
this.empty();
}
});
Why not replace textbox value onkeydown? It seems it would be more simples to just do txt1.text = txt2.text instead of appending the existing strings in txt1.
Something like this?
$('#t1').keydown(function(e) {
var char = (e.keyCode == 8) ? '' : String.fromCharCode(e.keyCode + (e.shiftKey ? 0 : 32));
$('#t2').val(char);
});
Related
I have a button that is enabled or disabled if, respectively, there is or is not text inside an input, as shown in the code snippet below:
var input = document.getElementById('myInput');
var btn = document.getElementById('myButton');
$(input).on('keyup', function(){
if((input.value != null) && (input.value != ''))
$(btn).removeClass('btnDisabled');
else
$(btn).addClass('btnDisabled');
});
Using keyup event it is working good in my aplication on an smarthphone with Android 6.0.1. But for some reason, on an tablet with Android 4.4.2 if backspace key are pressed till the begin of input, erasing all the text value, the button is still enabled.
I researched this problem but I'm still not sure if the WebView version interferes with this. I think so.
I used other code snippets to see if the event is triggered by the "backspace" button, as shown below:
$(input).on('keydown', function(event){ //I tried keyup, keydown and keypress
var key = event.keyCode || event.charCode;
console.log("keydown " + key, "length " + input.value.length);
//if(key == 8 && input.value.length == 1) $(btn).addClass('btnDisabled');
});
With this test I saw that the backspace does not trigger the event and the variable key is always equal to 0.
I need to disable the button when input is empty. Where am I going wrong?
Right now, I thank those who help! :D
There is another event that you can use: input
https://developer.mozilla.org/en-US/docs/Web/Events/input
The DOM input event is fired synchronously when the value of an <input>, <select>, or <textarea> element is changed.
In this case, change
$(input).on('keydown',
to
$(input).on('input',
See also: https://caniuse.com/#search=input
I'm trying to validate keycode entry by adding an alert when a user types a key that isn't expected, and then clearing the text area. The alert functions correctly but the text area isn't clearing.
I've checked the documentation here, but I can't see an area with my .val() line. I've also tried this: $("#noteNumberInput").attr('value', "");
Scenario: I type 1-9 in the text box and get no alert (works fine), if I type a letter a-z for example, the alert pops up but the letter remains in the text box.
EDIT:
Something I've noticed is that it does clear the textarea after the first key. If I type the letter 'a' and then 'b', the 'a' is removed and replaced with a 'b'.
HTML:
<textarea id="noteNumberInput" placeholder="Note number"></textarea>
JS:
var noteNumberInput = document.getElementById("noteNumberInput");
//VALIDATE NOTE NUMBER TEXTAREA
function validate(key) {
var keycode = (key.which) ? key.which : key.keyCode;
//comparing pressed keycodes
if (keycode === 8 || (keycode >= 48 && keycode <= 57)) {
return true;
}
if (keycode < 48 || keycode > 57) {
alert("Please only enter the note number e.g. 1, 2..14 etc.");
$("#noteNumberInput").val("");
return false;
}
}
noteNumberInput.addEventListener("keydown", validate);
When you do $("#noteNumberInput").val('');, it removes all the content of the textarea, so if that's not what is happening, the problem is probably somewhere else.
Change noteNumberInput.addEventListener("keydown", validate); to use keyup
Using $("#noteNumberInput").val() will clear the textarea
EDIT
The problem is the keydown handler. In this case the function will be triggered followed by the display of alert & then the text area will be populated. But on using keyup the function will be triggered on release of the key.So by that time the textarea will be populated with value.
Change the keydown to keyup
var noteNumberInput = document.getElementById("noteNumberInput");
noteNumberInput.addEventListener("keyup", validate);
DEMO
Your only asking for the validate() function to actually execute when you've pressed the next key.
I think that´s not the best idea to trigger key events, because cut and paste and drag and drop can also change the input element.
try this:
Element.addEventListener('input', function(){
this.value=this.value.replace(/[^0-9,.]/g, '');
});
this must be adapted to textarea...
I have two input fields i want to trigger keypress of one input field on keypress of another input field.
What i have tried is
$('#example').keypress(function(event) {
var press = jQuery.Event("keypress");
var code = event.keyCode || event.which;
press.which = code ;
$('#search').trigger(press);
});
both example and search are input fields. Why i am doing so i because when i enter text in simple field it has to enter text in another field which filters search results.
Try this :
JavaScript
$('#example').on('keypress keyup keydown',function(event) {
// create the event
var press = jQuery.Event(event.type);
var code = event.keyCode || event.which;
press.which = code ;
// trigger
$('#search').val(this.value);
$('#search').trigger(event.type, {'event': press});
});
// Omit - Check if search box reacts
$('#search').on('keypress keyup keydown',function(event) {
// sample
console.log(event.type);
});
Demo here : http://jsbin.com/pebac/1/edit
Note that even if you successfully manage to trigger a keypress event this doesn't act as a real one, meaning that the char won't be appended to the input.
Guess it's like $.click()
$('#search').keypress();
If all you want to do is to copy the content of one field to the other, I'd say it's better to do $('#search').val($(this).val()); instead of triggering the keypress event on #search.
In jQuery, how can I trigger the behavior of a user tabbing to the next input field?
I've tried this:
var e = jQuery.Event("keydown");
e.which = 9; // # Key code for the Tab key
$("input").trigger(e);
But triggering the event doesn't move the cursor to the next field.
I suppose I could move the cursor manually using focus(), but deciding which field should be next is something the browser already knows how to do, so it seems much cleaner to just trigger a tab.
Any ideas?
Here's one solution, via http://jqueryminute.com/set-focus-to-the-next-input-field-with-jquery/
$.fn.focusNextInputField = function() {
return this.each(function() {
var fields = $(this).parents('form:eq(0),body').find(':input').not('[type=hidden]');
var index = fields.index( this );
if ( index > -1 && ( index + 1 ) < fields.length ) {
fields.eq( index + 1 ).focus();
}
return false;
});
};
The use is as follows:
$( 'current_field_selector' ).focusNextInputField();
See the accepted answer to this question. If for example you want to move focus to the next field when a certain number of characters have been entered, you could use that code in the keyup event, and check the entered number of characters.
The code in that answer works by getting the set of inputs in the form, finding the selected input and adding 1 to the index of the selected input, and then triggering the focus event on the element with that index.
There's a JQuery plugin available:
http://www.mathachew.com/sandbox/jquery-autotab/
Have you tried using
$("input").trigger( 'keypress', e );
as a solution?
I find sometimes being explicit is best.
If that doesn't work possibly even
$("input").trigger( 'keypress', [{preventDefault:function(){},keyCode:9}] );.
Hope this helps.
I have a simple in-line edit in my grid, and I want to commit the change when the user tabs off the textbox. The default behavior of jqGrid forces the user to press 'Enter' to commit the change, but this is non-intuitive for our users.
onSelectRow: function(id) {
$(gridCoreGroups).editRow(id, true, undefined, function(response)
{
alert("hello world");
}
}
I've worked my way through the events provided, but they all happen as a result of the user pressing 'Enter', which I want to avoid. Is there something I can wire up that would trigger an action when the user tabs off this cell?
For in line editing you can accomplished this several ways. To bind an onblur event to the input field using the onSelectRow trigger, eliminating the need for edit and save buttons, do something like this:
$('#gridId').setGridParam({onSelectRow: function(id){
//Edit row on select
$('#gridid').editRow(id, true);
//Modify event handler to save on blur.
var fieldName = "Name of the field which will trigger save on blur.";
//Note, this solution only makes sense when applied to the last field in a row.
$("input[id^='"+id+"_"+fieldName+"']","#gridId").bind('blur',function(){
$('#gridId').saveRow(id);
});
}});
To apply a jQuery live event handler to all inputs that may appear within a row (jqGrid labels all inputs as rowId_fieldName ), loop throw the number of rows in your grid and do something like this:
var ids = $("#gridId").jqGrid('getDataIDs');
for(var i=0; i < ids.length; i++){
fieldName = "field_which_will_trigger_on_blur";
$("input[id^='"+ids[i]+"_"+fieldName+"']","#gridId").live('blur',function(){
$('#gridId').jqGrid('saveRow',ids[i]);
});
}
Note: To use blur with .live() like above, you'll need jQuery 1.4 or the patch located at:
Simulating "focus" and "blur" in jQuery .live() method
Be careful with rowIds. When you get into sorting, adding and removing of rows, you may find yourself writing some tricky jQuery to convert row ids to iRows or row numbers.
If you're like me and you went with individual cell edit, you'll want to modify the afterEditCell trigger with something like:
$('#gridId').setGridParam({afterEditCell: function(id,name,val,iRow,iCol){
//Modify event handler to save on blur.
$("#"+iRow+"_"+name,"#gridId").bind('blur',function(){
$('#gridId').saveCell(iRow,iCol);
});
}});
Hope that helps..
This is pretty horrible, but its my take on this problem, and is prob a bit easier and more generic - it presses enter programmatically when the item loses focus :)
afterEditCell: function() {
//This code saves the state of the box when focus is lost in a pretty horrible
//way, may be they will add support for this in the future
//set up horrible hack for pressing enter when leaving cell
e = jQuery.Event("keydown");
e.keyCode = $.ui.keyCode.ENTER;
//get the edited thing
edit = $(".edit-cell > *");
edit.blur(function() {
edit.trigger(e);
});
},
Add that code to your jqgrid setup code.
It assumes that the last edited item is the only thing with .edit-cell as a parent td.
My solution was to use basic jQuery selectors and events independently of the grid to detect this event. I use the live and blur events on the textboxes in the grid to capture the event. The two events are not supported in combination with each other, so this hack ended up being the solution:
Simulating "focus" and "blur" in jQuery .live() method
I know this question is old however the answer is outdated.
A global variable called lastsel must be created and the following added to the jqGrid code
onSelectRow: function (id) {
if (!status)//deselected
{
if ($("tr#" + lastsel).attr("editable") == 1) //editable=1 means row in edit mode
jQuery('#list1').jqGrid('saveRow', lastsel);
}
if (id && id !== lastsel) {
jQuery('#list1').jqGrid('restoreRow', lastsel);
jQuery('#list1').jqGrid('editRow', id, true);
lastsel = id;
}
},
I had the same issue and tried the answers above. In the end I went with a solution that inserts an "Enter" key press when the user is leaving the tab.
// Call this function to save and unfinished edit
// - If an input exists with the "edit-call" class then the edit has
// not been finished. Complete the edit by injecting an "Enter" key press
function saveEdits() {
var $input = $("#grid").find(".edit-cell input");
if ($input.length == 1) {
var e = $.Event("keydown");
e.which = 13;
e.keyCode = 13;
$input.trigger(e);
}
}
Instead of using selectRow use CellSelect.
onCellSelect: function (row, col, content, event) {
if (row != lastsel) {
grid.jqGrid('saveRow', lastsel);
lastsel = row;
}
var cm = grid.jqGrid("getGridParam", "colModel");
//keep it false bcoz i am calling an event on the enter keypress
grid.jqGrid('editRow', row, false);
var fieldName = cm[col].name;
//If input tag becomes blur then function called.
$("input[id^='"+row+"_"+fieldName+"']","#gridId").bind('blur',function(e){
grid.jqGrid('saveRow', row);
saveDataFromTable();
});
//Enter key press event.
$("input[id^='"+row+"_"+fieldName+"']","#gridId").bind('keypress',function(e){
var code = (e.keyCode ? e.keyCode : e.which);
//If enter key pressed then save particular row and validate.
if( code == 13 ){
grid.jqGrid('saveRow', row);
saveDataFromTable();
}
});
}
//saveDataFromTable() is the function which validates my data.