I am designing a chatbox with jQuery.
I want to attach a li that contains the user text to ul using 'Enter' key
(without PHP or any server), but it's not working.
My code looks like this:
var txt = "<b>me:</b>"+$(".usertext").val();
var myli = $("<li>").html(txt);
$('chav_box_in').keypress(function(e)
{
if ( $(".usertext").val() != "" )
{
if (e.keyCode == 13)
{
$("#send").click(function(){
$("#chatlog").append(myli);
$(".usertext").val("");
})
}
}
});
My chat.
You are creating a click event listener on your #send element each time you do a enter keypress, not actually firing that event.
If you are meaning to do a enter keypress and do a Send button click to add the messages you can make a single function and pass it as an argument to jQuery event listener methods
function appendChat(e) {
var id = e.target.id;
//variables for testing, you could have all of the
//comparisons in the 'if' statement, just using these to
//make the 'if' statement more clear
var notEmpty = $(".usertext").val() != "",
isEnterKeypress = e.type == "keypress" && e.keyCode == 13,
isSendClick = e.type == "click" && id == "send";
if( notEmpty && (isEnterKeypress || isSendClick) ) {
var txt = "<b>me:</b>"+$(".usertext").val();
$("#chatlog").append($("<li>").html(txt));
$(".usertext").val("");
}
}
$("#send").click(appendChat);
$(".chav_box_in").keypress(appendChat);
Demo
function appendChat(e) {
var id = e.target.id;
var notEmpty = $(".usertext").val() != "",
isEnterKeypress = e.type == "keypress" && e.keyCode == 13,
isSendClick = e.type == "click" && id == "send";
if( notEmpty && (isEnterKeypress || isSendClick) ) {
var txt = "<b>me:</b>"+$(".usertext").val();
$("#chatlog").append($("<li>").html(txt));
$(".usertext").val("");
}
}
$("#send").click(appendChat);
$(".chav_box_in").keypress(appendChat);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul id="chatlog"></ul>
<input class="usertext chav_box_in"><button id="send">Send</button>
You can't have event inside an event.
Remove that click event from keypress keeping code in there.
$('.chav_box_in').keypress(function(e)
{
if (e.keyCode == 13)
{
if ($(this).val ()!=""){
$("#chatlog").append(myli);
$(".usertext").val("");
}
}
});
Related
I'm trying to get the index of an input between a set of inputs. Basically, I have a table that contains, on more than one row, many inputs.
Once the user press the "enter" button, while the input is focused, I need to jump to the next input field, as the "tab" key do.
I was following this accepted response, and this is what I've done so far: Fiddle
CODE
$(document).keypress(function(e){
if( e.which == 13 && e.target.nodeName == 'INPUT'){
var inputs = $("#inputsTable input.td_in");
alert(inputs.index(this));
}
});
as you can see, every time you focus an input and then press ENTER, the popup msg says "-1"..
What am I doing wrong? I've been struggling with this piece of code for an hour, and I'm giving up.
I found out that replacing this with e.target also works.
CODE
$(document).keypress(function(e){
if( e.which == 13 && e.target.nodeName == 'INPUT'){
var inputs = $("#inputsTable input.td_in");
alert(inputs.index(e.target));
}
});
That's because this references the document, not your input.
Use .on(), and pass it an input.td_in selector:
$('#inputsTable').on('keypress', 'input.td_in', function (e) {
if( e.which == 13 ) {
var inputs = $("#inputsTable input.td_in");
alert(inputs.index(this));
}
});
P.S. You should probably cache that selector.
$(document).on('keypress', 'input', function (e) {
if( e.which == 13 ){
var inputs = $("#inputsTable input");
var the_index = inputs.index(this);
inputs[the_index+1].focus();
}
});
http://jsfiddle.net/5DwHw/1/
Is it possible to trigger a key event only outside a form element?
Background: I have a code that loads the next page when the right key is pressed. But I don't want to trigger that event if somebody is using that key in a form element.
current code:
$(document).keydown(function(e){
if (e.keyCode == 37) {
var url = $('a#left').attr("href");
if (url != '') { // require a URL
window.location = url; // redirect
}
return false;
}
if (e.keyCode == 39) {
var url = $('a#right').attr("href");
if (url != '') { // require a URL
window.location = url; // redirect
}
return false;
}
});
If you have other fields outside your form this might be quite useful I hope
LIVE DEMO
document.onkeyup = function( ev ){
var key = ev.which || ev.keyCode ,
aID = { 37:"left", 39:"right" };
if( ! (/INPUT|TEXTAREA/i.test(ev.target)) && aID[key]) {
var url = document.getElementById( aID[key] ).getAttribute('href');
window.location = url;
}
};
Here is a basic example of the concept. Your simply adding an event handler to the document and checking that its target does not have a parent that is a form.
HTML
<form>
Inside form
<input/>
</form>
Outside form
<input />
Javascript
$(document).keyup(function(event){
if($(event.target).parents("form").length == 0){
alert("here");
}
});
Working POC: http://jsfiddle.net/48NYE/
This concept can be easily applied to the script you have provided.
Modification for your Script
$(document).keydown(function(e){
var outsideForm = $(e.target).parents("form").length == 0;
if (e.keyCode == 37 && outsideForm) {
var url = $('a#left').attr("href");
if (url != '') { // require a URL
window.location = url; // redirect
}
return false;
}
if (e.keyCode == 39 && outsideForm){
var url = $('a#right').attr("href");
if (url != '') { // require a URL
window.location = url; // redirect
}
return false;
}
});
I'm calling a function (below) that will perform an action if the user presses the delete button. It is working fine but I need to to only do it on the page and not when a user is typing (inside an input or inside a textarea).
$(window).keydown(function (evt) {
if (evt.which == 46) { // delete
goDoSomething();
}
});
Any ideas how I can amend the above to not fire if the user is in an input or textarea?
Thanks in advance,
Dave
check evt.target's type:
$(window).keydown(function (evt) {
if (evt.target.tagName.toLowerCase() !== 'input' &&
evt.target.tagName.toLowerCase() !== 'textarea' && evt.which == 46) { // delete
goDoSomething();
}
});
You could have a global variable and set it to something when a textbox is focussed on and reset it on blur. Something like this:
var textboxSelected = false;
$(":input").focus(function () {
textboxSelected = true;
});
$(":input").blur(function () {
textboxSelected = false;
});
Then in your onKeyDown event check whether the variable is set to false before carrying out the rest of the functionality:
$(window).keydown(function (evt) {
if (evt.which == 46 && textboxSelected == false) {
goDoSomething();
}
});
try sometihing like this:
$(window).keydown(function (evt) {
if(evt.target != $('input') && evt.target != $('textarea')){
if (evt.which == 46) { // delete
goDoSomething();
}
}
});
document.onkeydown = function(event) {
var tagName = event.target.tagName;
if (tagName != 'INPUT' && tagName != 'TEXTAREA' && !event.alt && event.control) {
if (event.ctrlKey && event.keyCode == 37) {
if (_this.currentPage > 1) {
window.location.href = _this.baseUrl.replace(/%page%/i, _this.currentPage + 1);
}
} else if (event.ctrlKey && event.keyCode == 39) {
if (_this.currentPage < _this.pagesTotal) {
window.location.href = _this.baseUrl.replace(/%page%/i, _this.currentPage - 1);
}
}
}
}
This gives me an error only in IE 8:
'target' is null or not an object
for that line var tagName = event.target.tagName;
How to fix that? Error happens when I press Ctrl or arrows button.
IE does not pass in the event object into the event handler. Instead, they use the global event property of the window object. So for IE, you'd use window.event instead.
It is common practice to test for the supplied argument first. You also have to take into account the fact the IE uses srcElement instead of target. To account for all that, use something similar to this:
document.onkeydown = function(event) {
event = event || window.event;
var tagName = (event.target || event.srcElement).tagName;
// Keep up the good work...
}
This should do the trick.
Do it like this:
event = event || window.event;
var tagName = (event.target || event.srcElement).tagName.toUpperCase();
As you can see in the picture that if i click the selected tab "Navigation" then only the rename option is appearing (pic 2). I want to make this via key board.
JavaScript code:
_makeEditable: function() {
var instance = this;
if (instance._isModifiable) {
var currentItem = instance._navBlock.find('li.selected');
var currentLink = currentItem.find('a');
var currentSpan = currentLink.find('span');
currentLink.click(
function(event) {
if (event.shiftKey) {
return false;
}
}
);
You might want to try something like this:
prototype.js:
document.observe('keydown', mainWindowKeyDown);
jquery (not sure about this, I don't use jquery often):
$(function()
{
$(document).keydown(mainWindowKeyDown);
});
The keydown handler could be something like:
/*
Called when hitting any key.
*/
function mainWindowKeyDown(e)
{
if (e.keyCode == 113) // when F2 is pressed
triggerTabRename();
//else if (e.ctrlKey && e.keyCode == 90) // when ctrl + 'z' pressed
// doSomethingWhenCtrlZWasPressed(e);
//else if (e.ctrlKey && e.keyCode == 88) // when ctrl + 'x' pressed
// doSomethingWhenCtrlXWasPressed(e);
}
Here you can find a list of keycodes.