Override Default Tabbing Navigation - javascript

I am trying to use jquery to override the default tabbing navigation. I cannot simply use the tabindex property because I am trying to get the tab key to navigate from a text input to a virtualized textbox (codemirror). I have been trying to use the following javascript/jquery to no avail:
$('#modelName').focus(function() {
$(this).keydown( function(event) {
if(event.keyCode=='9') {
codeMirror.focus();
}
});
});
Any thoughts on how to make this work?

$('#modelName').keydown( function(event) {
if(event.keyCode == 9) {
event.preventDefault();
codeMirror.focus();
}else{
alert("Not the right key! " + event.keyCode);
}
});
It's good to have a catch, just so you can see where you're going wrong.
In this case, I think it's string vs int.
Also, the way your code is, you would be applying a new keydown event handler each time the #modelName gets focus, without removing the old one. Would likely cause problems later.

try this
$('#modelName').keyup(function (e) {
if(e.keyCode== 9){
codeMirror.focus();
}
});
use keyup() instead of keydown()

Related

JavaScript Alert not disappearing when ok is clicked

I have created a JQuery dynamic table here and I'm trying to implement input checking to make sure only the numbers are saved. The cell is updated either by clicking outside of it or by pressing the enter button and what I am trying to achieve is having an alert whenever an invalid input is entered.
The 'focusout' function alert is is working perfectly. The 'keypress' function alert on the other hand is behaving strangely, the alert message is popping out as normal however it doesn't go away no matter how many times I click ok.
According to console.log() the alert is triggering the 'focusout' function somehow. But even if that was the case, I don't understand how that is causing the error since the 'focusout' function works fine. I've tried to use $(this).focus() after the alert but this didn't work. Any Idea what I may be missing?
Thanks in advance
$(document).on('keypress', '.row_data', function (event) {
if (event.which === 13) {
event.preventDefault()
if (isNaN($(this).html())) {
alert("Enter valid number")
} else {
var elem = $(this)
saveValue(elem)
}
}
});
/* Saves the edited cell data when user clicks outside the cell */
$(document).on('focusout', '.row_data', function (event) {
event.preventDefault();
if (isNaN($(this).html())) {
alert("Enter valid number")
} else {
var elem = $(this)
saveValue(elem)
}
});
EDIT
So here is my HMTL for context. I am using Handlebars to create a table but basically all my cells are like this..
<span class="row_data" edit_type="click" col_name="col_1">{{col_1}}</span>
</td>
<td>£
<span class="row_data" edit_type="click" col_name="col_2">{{col_2}}</span>
</td>
<td>£
<span class="row_data" edit_type="click" col_name="col_3">{{col_3}}</span>
</td>
and I'm using JQuery to make the cells editable like this...
/* Makes each cell on the table editable */
$(document).on('click', '.row_data', function (event) {
event.preventDefault();
if ($(this).attr('edit_type') === 'button') {
return false;
}
$(this).closest('span').attr('contenteditable', 'true');
$(this).css("background-color", "beige").css('padding', '5px');
$(this).focus();
})
I've made some changes below to your code and have commented on it fully. It's best to not repeat code whenever possible, and just maintain a single function and trigger that using various methods rather than having to ensure two different functions are maintained separately.
You are currently triggering your alert multiple times, we can rationalize the code a bit to avoid the two different functions triggering the warning.
I think you can simplify things by using:
$(":focus").blur();
This removes the focus from whichever element is in focus.
I've assumed your .row_data is an input, so have also used .val() rather than .html(), you might need to change this back depending on your use case.
Let me know if you were hoping for something else.
// I would recommend using keyup rather than keypress
$(document).on('keyup', '.row_data', function(event) {
// Check if it is a return
if (event.which === 13) {
// Remove focus
// This will triger the function below, it'll be easier to manage a single function
$(':focus').blur();
// Prevent default
event.preventDefault()
}
});
/* Saves the edited cell data when user clicks outside the cell */
$(document).on('focusout', '.row_data', function(event) {
// Prevent default
event.preventDefault();
// Check if NaN
// Used .val() - not sure if you need to use .html in your use case
if (isNaN($(this).val())) {
// Notify user
alert("Enter valid number")
} else {
// Pass element to save
saveValue($(this))
}
});
// Test saving function
function saveValue(elem) {
// Send to console to prove it works
console.log("Saving " + elem.val());
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="row_data">
Hi having your HTML here will help suggest a better soultion, but the simple guess is that you are creating a loop, with your events.
You said the keypress event is the problem, just for testing purposes have you tried changing keypress to keydown/keyUp.
Also i sugges changing the alert to console.log, for easier debuging.

Add "preventDefault" to all labels that uses specific Umbraco template

I'm having an issue with one of my main templates in umbraco.
The issue is that, whenever I'm logged in on my website and I hit the 'enter' key whilst focus is on an input label, I'm logged out and redirected to my startpage.
I know that the event.preventDefault() method will stop this, but I cannot figure out how to apply it in my scenario.
Is it possible to add a script to my Umbraco template that adds the "preventDefault()" in case of keyCode == 13 (the enter key)? And if so, how exactly?
I have a bunch of labels in all kinds of macros that uses this template, and I would very much prefer not to add these lines manually for each of them!
I have tried quite a lot of variation of the following, but without any luck:
$("input").click(function(e)
{
if(e.keyCode == 13) {
preventDefault();
}
});
Thank you for your time.
You check the keyCode on a click, that won't work. Also, the preventDefault() should be used on the event: e.preventDefault().
Use this instead for global enter key:
$(document).ready(function() {
$(window).keydown(function(event){
if(event.keyCode == 13) {
event.preventDefault();
return false;
}
});
});

How to stop CodeMirror from moving cursor on keyup?

I want to skip certain, uneditable (XML-)tags in my code, using CodeMirror. In order to do that, I have to 'stop' (preventDefault) the keyup event, do some logic and move the cursor. PreventDefault and codemirrorIgnore don't work or do not do what I need them to do. Do I have to catch the event outside CodeMirror? :(
Does not work:
codeMirror.on('keyup', function (cm, ev) {
ev.codemirrorIgnore = true;
ev.preventDefault();
return false;
});
By using the below code you can handle the up arrow functionality
codeMirror.setOption("extraKeys", {"Up":function()
{
console.log("Key Up pressed");
if(true) // logic to decide whether to move up or not
{
return CodeMirror.PASS;
}
}});
It sounds like what you actually want is markText with the atomic and readOnly options, rather than messing with key events (which won't really prevent the user from entering/editing the text).

jQuery keypress to work normally except hitting enter

I would like to trigger a click if enter is pressed inside an input tag, but would like to have the default event strategy in all other cases. I have tried it this way:
$("#keywords").keypress(function(e) {
if (e.charCode === 13) {
$("#campus-search").click();
} else {
$("#keywords").val($("#keywords").val() + String.fromCharCode(e.charCode));
}
});
It works, but I am still not satisfied, because when I click inside the input somewhere in the middle of text or press the left button, or home button and then try to type some text, it will show it at the end of the input, which is bad user-experience. Can I keep the input to work in the default way except the case when enter is pressed?
I think what you are looking for is this:
$(document).ready(function () {
$("#test").keyup(function (event) {
if (event.keyCode == 13) {
$("#campus-search").click();
}
});
$("#campus-search").click(function () {
console.log("BUTTON IS CLICKED");
});
});
The input will act completely normal and everything works on default, unless when you press the enter button (keyCode = 13), then the button .click() event will be triggered.
Working Fiddle: http://jsfiddle.net/Mz2g8/3/
————
# Update: Just one hint for the code in your question, do not use charCode, as it is deprecated.
This feature has been removed from the Web. Though some browsers may still support it, it is in the process of being dropped. Do not use it in old or new projects. Pages or Web apps using it may break at any time.
(E.g. charCode does not work with FF v29.0.1)
And something different but important to know:
charCode is never set in the keydown and keyup events. In these cases, keyCode is set instead.
Source: https://developer.mozilla.org/en-US/docs/Web/API/event.charCode
This should work
$("#keywords").keypress(function(e) {
if (e.charCode === 13) {
e.preventDefault(); // prevent default action of the event if the event is keypress of enter key
$("#campus-search").click();
} else {
$("#keywords").val($("#keywords").val() + String.fromCharCode(e.charCode));
}
});
I think you can eliminate the else clause entirely to get your desired result.
Look at this jsfiddle.
The keypress function does not capture non-printing keys, such as shift, esc, delete, and enter, so the best way to go about this would be have two event handlers: one for keypress, as you have defined above, and one for keydown that checks for the charCode 13 and then performs the click() event on $(#campus-search) if that keycode is passed (by an enter press).
Demo
This is what you are looking for:
HTML:
<input id="keywords" type="text" value="" />
<input id="campus-search" type="button" value="Campus Search" />
JavaScript / jQuery:
$("#keywords").keypress(function (e) {
if (e.charCode === 13) {
$("#campus-search").click();
} else {
$("#keywords").val($("#keywords").val() + String.fromCharCode(e.charCode));
}
});
$("#campus-search").on("click", function () {
alert("Searching..");
});
Live Demo

Jquery : how to trigger an event when the user clear a textbox

i have a function that currently working on .keypress event when the user right something in the textbox it do some code, but i want the same event to be triggered also when the user clear the textbox .change doesn't help since it fires after the user change the focus to something else
Thanks
The keyup event will detect if the user has cleared the box as well (i.e. backspace raises the event but backspace does not raise the keypress event in IE)
$("#inputname").keyup(function() {
if (!this.value) {
alert('The box is empty');
}
});
jsFiddle
As Josh says, this gets fired for every character code that is pressed in the input. This is mostly just showing that you need to use the keyup event to trigger backspace, rather than the keypress event you are currently using.
The solution by Jonathon Bolster does not cover all cases. I adapted it to also cover modifications by cutting and pasting:
$("#inputname").on('change keyup copy paste cut', function() {
//!this.value ...
});
see http://jsfiddle.net/gonfidentschal/XxLq2/
Unfortunately it's not possible to catch the cases where the field's value is set using javascript. If you set the value yourself it's not an issue because you know when you do it... but when you're using a library such as AngularJS that updates the view when the state changes then it can be a bit more work. Or you have to use a timer to check the value.
Also see the answer for Detecting input change in jQuery? which suggests the 'input' event understood by modern browsers. So just:
$("#inputname").on('input', function() {
//!this.value ...
});
Another way that does this in a concise manner is listening for "input" event on textarea/input-type:text fields
/**
* Listens on textarea input.
* Considers: undo, cut, paste, backspc, keyboard input, etc
*/
$("#myContainer").on("input", "textarea", function() {
if (!this.value) {
}
});
You can check the value of the input field inside the on input' function() and combine it with an if/else statement and it will work very well as in the code below :
$( "#myinputid" ).on('input', function() {
if($(this).val() != "") {
//Do action here like in this example am hiding the previous table row
$(this).closest("tr").prev("tr").hide(); //hides previous row
}else{
$(this).closest("tr").prev("tr").show(); //shows previous row
}
});
Inside your .keypress or .keyup function, check to see if the value of the input is empty. For example:
$("#some-input").keyup(function(){
if($(this).val() == "") {
// input is cleared
}
});
<input type="text" id="some-input" />

Categories

Resources