Send a message when pressing Enter - javascript

Here is my code:
<input type=\"text\" id='MsgToSend" + ToClient + "t" + FromClient + "' onkeypress='ClientOnTyping();' />
where the FromClient and the ToClient are dynamically generated.
JavaScript:
function ClientOnTyping() {
if(e.keyCode==13) {
// i know i should do this but my problem is what is 'e' in my case how can i specify it ?
}
}

You need to attach an event listener on the element for keydown event.
var btn = document.getElementById('MsgToSend');
btn.addEventListerner('keydown', function (e) {
if(e.keyCode==13) {
// i know i should do this but my problem is what is 'e' in my case how can i specify it ?
}
});
On traditional browsers, you can attach the event handler this way.
var btn = document.getElementById('MsgToSend');
btn.onkeydown = function (e) {
e = e || window.event;
var keyCode = e.keyCode || e.which;
if(keyCode==13) {
// i know i should do this but my problem is what is 'e' in my case how can i specify it ?
}
});

In the scope of the handler function, e is an event object created automatically whenever an event fires in the DOM. You need to simply pass it to your handler.
For example:
<input ...onkeypress="ClientOnTyping(event);">
and
function ClientOnTyping(e) {
...
}
Also, consider using unobtrusive code instead of obtrusive. See Difference between obtrusive and unobtrusive javascript and Starx's answer.

Related

onkeydown event variable breaking the EventListener code

I have the following Javascript code:
var field = document.createElement("INPUT");
field.type = "text";
field.addEventListener("blur", function() {
// stuff that works
(e ? e : window.event).stopPropagation();
return false;
};
field.addEventListener("keydown", function() {
alert("1");
if (e) {
alert("2");
} else {
alert("3");
e = window.event;
}
alert("4");
if (e.keyCode === 13) {
this.blur();
}
return true;
}
The input field is not inside a form. Pressing enter or going out of focus is meant to submit the field value to the server (existing code I can't change). The onblur event works but the onkeydown event is not. alert("1") is executed exactly but that's all. Nothing else happened.
I have tried experimenting around and my guess is that the mere existence of e is breaking the code. I have no idea how: don't all event listeners pass an e parameter to the function being called? What's going on here? How can I resolve this?
No jQuery please, it's not available.
You are not accepting an e parameter.
In your working event, you're using e if it exists (which it wont), or falling back to window.event if it doesn't:
(e ? e : window.event)
Similar checks do not exist in the broken event listener.
Make sure you accept a parameter named e:
field.addEventListener("keydown", function(e) {
... and it will be available in your code.

Event listener - click and mouseover?

So basically I am trying to put together some simple event listeners. I've added a button with the ID of "btn" in my HTML file, and basically I want to add a mouseover event, and a click event. I know how to do this, however I want to alert when each event occurs. Is there a way to neaten my code and put this all into one function instead of two? I'm just not sure how I would create two separate alert statements otherwise on the same button. Thanks!
You can define a single function and then reference it as the 2nd argument to .addEventListener.
Example:
<button id='btn' value='some button'>some button</button>
<div id='placeholder'></div>
<script>
(function() {
var btn = document.getElementById("btn");
btn.addEventListener("click",doSomething,false);
btn.addEventListener("mouseover",doSomething,false);
})();
function doSomething(e) {
// example: update the div with the event type
var p=document.getElementById("placeholder");
p.innerHTML=e.type;
}
</script>
JSFIDDLE DEMO
Maybe this will help?
The code below can be improved by adding another argument to determine add/remove, turning the two functions into one, but you get the idea.
(function() {
var btn = document.getElementById("btn");
addEvent(btn, "click mouseover", handler);
function handler ( event ) {
alert("This is the " + event.type + " handler.");
}
})();
function addEvent ( element, event, fnc ) {
var events = event.split(/\s/),
evt = "";
while ( evt = events.shift() ) {
((element.addEventListener) ? element.addEventListener(evt, fnc, false) : element.attachEvent("on" + evt, fnc));
}
}
function removeEvent ( element, event, fnc ) {
var events = event.split(/\s/),
evt = "";
while ( evt = events.shift() ) {
((element.removeEventListener) ? element.removeEventListener(evt, fnc, false) : element.detachEvent("on" + evt, fnc));
}
}
<button id="btn" type="button">Click or Hover</button>
I think this is what you want:
var myfunc = function(event) {
var btn...
btn.addEventListener(event, function()...
}
After you can call it like this:
Myfunc("click");

can not find the solution to my "addEventListener" function

I am stuck on problem where I try to utilies the addEventListener.
I did try to find solutions on the web but I think my knowledge is to limited to pick the suitable answer.
What I tried is to invoke a function "addFile()" when a key is pressed in this example enter(13) unfortunatly nothing happens. I could add the onkeypress attribute to the input "add-file" with a slightly edited addFileOnKeyEvent(event) but I'm trying to understand what is wrong with my eventListener.
I hope you could follow my explanation, as this is my first question. :)
function addFile() {
var x = document.getElementById("add-file").value;
x = x + ".xml";
var lbl = document.createElement("label");
var node = document.createTextNode(x);
lbl.appendChild(node);
var element = document.getElementById("appendable");
element.appendChild(lbl);
}
function addFileOnKeyEvent(event) {
var evt = event.keyCode;
var textField = document.getElementById("add-file").addEventListener("keypress", function() {
if (evt == 13) {
addFile();
}
});
}
<label>Dateien</label>
<input id="add-file" type="text" onclick="this.select();">
<button type="submit" onclick="addFile()">Hinzufügen</button>
<div class="data-display">
<span id="appendable"></span>
</div>
At first, addFileOnKeyEvent() is never called before anywhere. So you must call it when you try to add file. Or you must bind the event to the text field by default.
Also need not pass event object to addFileOnKeyEvent(). The event must be captured in the addEventListener callback function.
function addFile() {
var x = document.getElementById("add-file").value;
x = x + ".xml";
var lbl = document.createElement("label");
var node = document.createTextNode(x);
lbl.appendChild(node);
var element = document.getElementById("appendable");
element.appendChild(lbl);
}
function addFileOnKeyEvent() {
document.getElementById("add-file").addEventListener("keypress", function(event) {
var evt = event.keyCode;
if (evt == 13) {
addFile();
}
});
}
// call the function here
addFileOnKeyEvent();
// else just put the event handler part alone. The function is unnecessary here.
<label>Dateien</label>
<input id="add-file" type="text" onclick="this.select();">
<button type="submit" onclick="addFile()">Hinzufügen</button>
<div class="data-display">
<span id="appendable"></span>
</div>
That's not how events work. Try this...
document.getElementById("add-file").addEventListener(
"keypress",
function(event) {
if (event.keyCode == 13) {
addFile();
}
});
Instead of...
function addFileOnKeyEvent(event) {
var evt = event.keyCode;
var textField = document.getElementById("add-file").addEventListener("keypress", function() {
if (evt == 13) {
addFile();
}
});
}

JavaScript keypress event not raised on Android browser

I have created a simple code to handle keypress event:
var counter = 0;
$('input').on('keypress', function () {
$('div').text('key pressed ' + ++counter);
});
JSFiddle.
But keypress event handler is not raised on mobile browser (Android 4+, WindowsPhone 7.5+).
What could be the issue?
I believe keypress is deprecated now. You can check in the Dom Level 3 Spec. Using keydown or keyup should work. The spec also recommends that you should use beforeinput instead of keypress but I'm not sure what the support of this is.
Use the keyup event:
// JavaScript:
var counter = 0;
document.querySelector('input').addEventListener('keyup', function () {
document.querySelector('div').textContent = `key up ${++counter}`;
});
// jQuery:
var counter = 0;
$('input').on('keyup', function () {
$('div').text('key up ' + ++counter);
});
Use jQuery's input event, like this:
$( 'input' ).on( 'input', function() {
...
} );
With this you can't use e.which for determining which key was pressed, but I found a nice workaround here: http://jsfiddle.net/zminic/8Lmay/
$(document).ready(function() {
var pattForZip = /[0-9]/;
$('#id').on('keypress input', function(event) {
if(event.type == "keypress") {
if(pattForZip.test(event.key)) {
return true;
}
return false;
}
if(event.type == 'input') {
var bufferValue = $(this).val().replace(/\D/g,'');
$(this).val(bufferValue);
}
})
})
Yes, some android browser are not supporting keypress event, we need use to only keydown or keyup but will get different keycodes, to avoiding different key codes use the following function to get the keycode by sending char value.
Eg:
function getKeyCode(str) {
return str && str.charCodeAt(0);
}
function keyUp(){
var keyCode = getKeyCode("1");
}
I think it is bad idea to use other events in place of 'keypress'.
What you need to do is just include a jQuery file into your project.
A file named jQuery.mobile.js or quite similar (ex. jQuery.ui.js) of any version can help you.
You can download it from : https://jquerymobile.com/download/

Problem with event handler

function getFieldName(e) {
e = e || window.event;
var key = e.keyCode || e.which,
target = e.target || e.srcElement;
alert(target.name);
return (key != 13);
}
I have the above function called on body tag onkeypress = getFieldName(event);
I get the name of desired field but not able to check in IE as well as FF
if(target.name == 'check') {
// works fine in FF but in IE I'm not able
// to come inside this if-block, please suggest
}
thanks
I see you've tagged this post as jQuery... If you actually use jQuery to manage the event handler then you can use e.which to find the key that was pressed and e.target to find the DOM target. It also worries about the cross-browser stuff for you.
To attach a function as an event handler, you can follow this simple example:
$(document).keypress(getFieldName);
jQuery already normalizes some event properties internally, so you can just use event.target and event.which, you don't need to check for others, like this:
$(document).keypress(getFieldName);
function getFieldName(e) {
alert(e.target.name);
if(e.which == 13) {
alert("Key pressed was enter");
} else {
alert("Key pressed was not enter");
}
}
​
You can view a quick demo here

Categories

Resources