Getting Textbox Cursor Position (Before or After text) - javascript

How do I check to see if the cursor position is in the front of the text or the last of the text.
<script type="text/javascript">
$(document).ready(function () {
$('input').keyup(function (e) {
if (e.which == 39 && <CURSOR IS FIRST OR LAST OF TEXT>) {
alert($('input').val);
$(this).closest('td').next().find('input').focus();
$(this).closest('td').next().find('input').select();
}
}
}
<script>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('input').keyup(function (e) {
if (e.which == 39 && <selected text lenght> > 0) {
$(this).closest('td').next().find('input').focus();
$(this).closest('td').next().find('input').select();
}
else if (e.which == 37) {
$(this).closest('td').prev().find('input').focus();
$(this).closest('td').prev().find('input').select();
}
else if (e.which == 40) {
$(this).closest('tr').next().find('td:eq(' + $(this).closest('td').index() + ')').find('input').focus();
$(this).closest('tr').next().find('td:eq(' + $(this).closest('td').index() + ')').find('input').select();
}
else if (e.which == 38) {
$(this).closest('tr').prev().find('td:eq(' + $(this).closest('td').index() + ')').find('input').focus();
$(this).closest('tr').prev().find('td:eq(' + $(this).closest('td').index() + ')').find('input').select();
}
});
});

You can use jQuery Caret plugin. Check this thread here and the plugin's homepage. You can then change your code to:
var pos= $(this).caret().start == $(this).caret().end ? $(this).caret().start : -1;
if (e.which === 39 && (pos === 0 || pos === $(this).val().length)) {
...
Hope it helped,
Shakib

Related

EventListener keyup and keydown overlap when type fast

i inserted inputs in a fieldset with max-length equals to 1 and i added to each of them a keyup and keydown event through eventListener. The problem appears when i type characters fast and the first character is duplicated.
`
document.addEventListener('DOMContentLoaded', () => { // everything is loaded
var after, before;
inputList = document.querySelectorAll('input[type=text][maxlength="1"]');
inputList.forEach(element => {
element.addEventListener('keydown', () => {
before = element.value;
});
element.addEventListener('keyup', (event) => {
after = element.value;
if(event.keyCode === 37) {
element.previousElementSibling.focus();
return;
}
if(event.keyCode === 39) {
element.nextElementSibling.focus();
return;
}
if(after.length == 1 && before.length == 0) {
try {
element.nextElementSibling.focus();
return;
} catch(TypeError) {
return;
}
}
if(event.keyCode === 8) {
element.previousElementSibling.focus();
return;
}
alert(event.keyCode);
if(before.length === 1 &&
((event.keyCode >= 65 && event.keyCode <= 90) || (event.keyCode >= 97 && event.keyCode <= 122) || (event.keyCode >= 48 && event.keyCode <= 57))
) {
element.nextElementSibling.value = String.fromCharCode(event.keyCode);
element.nextElementSibling.focus();
return;
}
});
})
});

Why jQuery keyup is not working while I try to build keyboard shortcut on my website?

I'm trying to build keyboard shortcuts for accessibility in my website. For example, when user presses '1' I want to move him to the home. When user presses '2', to a different page.
I'm trying to use keyup for this but it's not working.
$(function() {
$(document).keyup(function(e) {
if (e.which == 1) {
console.log('1');
window.location.href = '/';
} else if (e.which == 2) {
window.location.href = '/escolas';
} else if (e.which == 3) {
window.location.href = '/noticias';
} else if (e.which == 4) {
window.location.href = '/eventos';
} else if (e.which == 5) {
window.location.href = '/contato';
}
});
});
Can someone help me? It's not logging 1 when I press '1'.
It is because the key code for '1' is not 1 but 49 (or 97 for the one on the numpad).
Check this to see your key code:
$(function() {
$(document).keyup(function(e) {
$('body').text(e.type + ' ' + e.which);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
You can get the key character by String.fromCharCode(event.which);, and then directly compare with actual character:
$(function() {
$(document).keyup(function(e) {
if (e.key) {
var key = e.key;
} else {
var key = String.fromCharCode(e.which || e.keyCode);
}
if (key == 1) {
console.log('1');
window.location.href = '/';
} else if (key == 2) {
window.location.href = '/escolas';
} else if (key == 3) {
window.location.href = '/noticias';
} else if (key == 4) {
window.location.href = '/eventos';
} else if (key == 5) {
window.location.href = '/contato';
}
});
});
You are using wrong keycodes. Refer this
$(function() {
$(document).keyup(function(e) {
if (e.which == 49) {
console.log('1');
window.location.href = '/';
} else if (e.which == 50) {
window.location.href = '/escolas';
} else if (e.which == 51) {
window.location.href = '/noticias';
} else if (e.which == 52) {
window.location.href = '/eventos';
} else if (e.which == 53) {
window.location.href = '/contato';
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
e.which gives you ASCII value. To convert ASCII into character use String.fromCharCode(e.which).
$(function () {
$(document).keyup(function (e) {
if (String.fromCharCode(e.which) == 1) {
window.location.href = '/';
} else if (String.fromCharCode(e.which) == 2) {
window.location.href = '/escolas';
} else if (String.fromCharCode(e.which) == 3) {
window.location.href = '/noticias';
} else if (String.fromCharCode(e.which) == 4) {
window.location.href = '/eventos';
} else if (String.fromCharCode(e.which) == 5) {
window.location.href = '/contato';
}
});
});
If you wanna go fancy:
$(document).ready(function() {
'use strict';
const addresses = [
{
codes: [49, 97],
path: '/'
},
{
codes: [50, 98],
path: '/escolas'
},
{
codes: [51, 99],
path: '/noticias'
},
{
codes: [52, 100],
path: '/eventos'
},
{
codes: [52, 101],
path: '/contato'
}
]
$(document).on("keyup", evt => {
const key = evt.which;
addresses.map(address => {
if(address.codes.filter(code => code === key).length)
window.location.href = address.path;
})
});
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Jquery Tab panel to get focus on key press

I have a jquery tab panel. This panel contains some user controls like textboxes. My requirement is to set focus on tab when I press Shift+T. This is not happening. I have used the following code.
<script type="text/javascript">
$(document).ready(function () {
$("#tabs").keypress(function () {
if (e.keyCode == 80 && e.keyCode == 18)
$("#tabs").focus();
});
$("#tabs").focus(function () {
if (e.keyCode == 37) {
selected = (selected - 1);
$('#tabs').tabs('option', 'selected');
}
if (e.keyCode == 39) {
selected = (selected + 1);
$('#tabs').tabs('option', 'selected');
}
});
});
</script>
I am not sure why you need to complicate it.
Try this demo:
http://jsfiddle.net/lotusgodkk/GCu2D/417/
JS:
$(document).ready(function () {
$(document).on('keydown', function (e) {
var keyCode = e.keyCode;
if ((keyCode == 84) & (e.shiftKey)) {
$('.ui-state-active:visible:first').focus(); //ui-state-active is the class of active tab.
}
});
$('#tabs').tabs();
});
you should try this:
inputs = $("table :input");
$(inputs).keypress(function(e){
if (e.keyCode == 13){
inputs[inputs.index(this)+1].focus();
}
});
i guess might be work for u Click Here
js
$("#status").keydown(function (e) {
if (e.which == 9) {
$("#statuses").html(this.value);
this.value = "";
$("#status").focus();
e.preventDefault();
}
});
first -> remove double qoutes .. they are used for components like input, p etc.
second -> try this code..
$(document).ready(function () {
$('#tabs').keypress(function () {
if (e.keyCode == 80 && e.keyCode == 18)
$('#tabs').focus(); // setting the focus
alert("working"); //test it
});
$('#tabs').focus(function () {
if (e.keyCode == 37) {
selected = (selected - 1);
$('#tabs').focus(); // setting the focus
$('#tabs').tabs('option', 'selected');
}
if (e.keyCode == 39) {
selected = (selected + 1);
$('#tabs').tabs('option', 'selected');
}
});
});
</script>

Jquery function not being called on Page unload

<input type="submit" name="Post" value="Post" class="btm-bg" />
<script type="text/javascript" src="../Scripts/jquery-1.9.0.min.js"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"> </script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/mvcfoolproof.unobtrusive.min.js")" type="text/javascript"></script>
$(function () {
$('.option').hide();
$('input[class="Tproperty"]').click(function () {
$('.option').hide();
if ($(this).val() == '2' || $(this).val() == '8') {
$('#Display').show();
$('#residential').hide();
$('#amen').hide();
}
if ( $(this).val() == '5') {
$('#Display').show();
$('#residential').hide();
$('#amen').hide();
$('#xtrafac').hide();
$('#parkings').hide();
$('#rooms').hide();
$('#bathrooms').hide();
}
else {
$('#Display').show();
$('#residential').show();
$('#amen').show();
$('#xtrafac').show();
$('#parkings').show();
$('#rooms').show();
$('#bathrooms').show();
}
});
});
$('form').on('submit', function () {
alert("hello");
var sr = $("input[name = saleorrent]:checked").val();
alert(sr);
var mr = $("input[name = Monthlyrent]").val();
alert(sr + mr);
if (sr == "Rent" && mr == null ) {
alert("Enter monthly rent");
e.preventDefault();
}
});
$(function () {
$('.showes').hide();
$('input[class="saleorrent"]').click(function () {
$('.showes').hide();
if ($(this).val() == 'Sale') {
$('#optionsale').show();
$('#sale').show();
$('#rent').hide();
}
else {
$('#optionRent').show();
$('#sale').hide();
$('#rent').show();
}
});
});
function CheckNumeric(e) {
if (window.event) // IE
{
if ((e.keyCode < 48 || e.keyCode > 57) & e.keyCode != 8) {
event.returnValue = false;
return false;
}
}
else { // Fire Fox
if ((e.which < 48 || e.which > 57) & e.which != 8) {
e.preventDefault();
return false;
}
}
}
$(function () {
$("#City").change(function () {
if ($("#City").val() != 0) {
var ddlCityId = $(this).val();
var subItems = "";
$.getJSON("#Url.Action("ddlCities", "Listings")", { id: ddlCityId },
function (data) {
$.each(data, function (index, item) {
subItems += "<option value='" + item.Locality_Id + "'>" + item.Locality + "</option>"
});
$("#Locality").html(subItems)
});
}
else {
alert("false");
}
});
});
I am using MVC 4.0 . I want an alert message if the field is left empty. But the thing is as soon as I click the submit button it reaches out to the server side and not executing the jquery code before unloading the page.
beforeunload fires after a form submission as the form submission can be cancelled. You need to stop the form submission instead. e.g. like:
$('form').on('submit', function () {
alert("hello");
var sr = $("input[name = saleorrent]:checked").val();
alert(sr);
var mr = $("input[name = Monthlyrent]").val();
alert(sr+ mr);
if (sr == 'Rent' && mr == " ")
{
alert("Enter monthly rent");
e.preventDefault(); // <<<<<< Stop the form submission
}
});
Notes:
Always use prop('checked') with checkboxes.
var sr = $("input[name=saleorrent]").prop('checked');

jquery keypress: trigger click when ctl+x and ctl+s

I am trying to update and close a popup by using keypress.
if keypress - ctl+s = save
if keypress - ctl+x = exit
$(window).keypress(function(event) {
if ((event.which == 120 && event.ctrlKey) || (event.which == 19)){
$(".ps-button-close",object_popup).click();
//alert("Keys down are Ctrl + x + Return");
} else if((event.which == 115 && event.ctrlKey) || (event.which == 19)) {
// Trigger click.
("form.ps-item-form.page input[type=submit][name=update]",object_popup).click();
} else {
return true;
}
event.preventDefault();
return false;
});
But they don't work at all...
Any ideas how I can combine them perfectly?
edit:
seems to get them worked now...
if ((event.which == 115 && event.ctrlKey) || (event.which == 19)) {
// Trigger click.
$("form.ps-item-form.page input[type=submit][name=update]",object_popup).click();
} else if ((event.which == 120 && event.ctrlKey) || (event.which == 19)){
// Trigger click.
$(".ps-button-close",object_popup).click();
//alert("Keys down are Ctrl + x + Return");
} else {
return true;
}
Use
$("form input[type=submit] [name=update]").trigger('click');

Categories

Resources