I'm trying to force a keypress inside a textfield using Javascript. This has to work specifically on IE but it simply doesn't work.
Can anyone help me?
My test script is this one:
<html>
<body>
<input type="text" id="txtfld">
<input type="button" onclick="go()">
<script>
function go() {
var q = document.getElementById('txtfld');
q.style.backgroundColor='yellow';
q.focus();
var evObj = document.createEventObject();
evObj.keyCode = 84; // [T] key
q.fireEvent('onkeypress', evObj);
}
</script>
</body>
</html>
It's not a good idea to try to drive browsers' default-event-actions by faking events. In as much as it can be done at all it is browser-specific and unreliable.
If you want to add a letter âtâ to the field, say so:
q.value+= 't';
In more complicated cases like if you want to insert a letter at the current cursor position, you need branching code for document.selection (IE) and field.selectionStart/End (others).
Related
Hi I want to simulate a user clicking on an input box.
script is:
function prepareToScan(){
$("fireRegAdd").focus();
$('fireRegAdd').keypress();
}
and HTML is
<h2>Add a visitor to today's fire register</h2>
<input type="button" onmousedown="prepareToScan()" value="Add Visitor">
<input id="fireRegAdd" name="fireRegAdd">
</div>
I have a barcode scanner which puts the code into the input box but only when it's been "clicked". I've tried .focus() but it needs two scans to get the scan to work. The on focus is not the same as actually clicking in the box. Does any one know how to do that?
thanks
So I've found that if I add in an alert it set it correctly :
function prepareToScan(){
alert("ready to scan");
$("fireRegAdd").focus();
$('fireRegAdd').keypress();
}
but I don't really want an alert box
I've added a demo of the code. When you click on the button I want there to be a blinking cursor in the input box.
function prepareToScan(){
$("#fireRegAdd").focus();
$('#fireRegAdd').click();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div>
<h2>Add a visitor to today's fire register</h2>
<input type="button" value ="Add Visitor" onmousedown="prepareToScan()"/>
<input id="fireRegAdd" name="fireRegAdd" value="" />
</div>
I've discovered that it's virtually impossible to focus on an input box so that the curso blinks. I tried everything including manipulating the cursor position and using a click event.
I did however solve my problem. Barcode scanners act like keyboards. So I wrote some code which detects keyboard input. It checks for incoming keys. If it receives more than 3 in 250 ms it assumes that it is coming from the scanner. Works a treat. It'd be easy to modify to adjust for different applications. Here's the javascript code I ended up with. To make it work you need a div with id="barcode" Hope someone finds it useful.
var chars = [];
var pressed = false;
window.addEvent( 'keydown', function( evt ){
//console.log(evt.key);
chars.push(evt.key);
setTimeout(function(){
if (chars.length >= 3) {
var barcode = chars.join("");
$("barcode").value= barcode;
}
chars = [];
pressed = false;
},250);
});
I want to generate a virtual keyboardEvent(tab). I did some research on the same and got few usefully answers, however it not working for me. I understand that Javascript is event driven programming language so User should press require key, but I also want to understand that can we generate an keyboard event through JavaScript.
function fnGenerateTabKeyEvent() {
var e = document.createEventObject("KeyboardEvent");
e.keyCode = 9; // tab's ASCII
document.getElementsByName("someTxtBox").fireEvent("onkeyup", e);
}
<input type="text" id="someTxtBox"/>
It's not working in IE8 and I'm not getting any error either. I just want that whenever I can this function it should an keyboardevent(tab) from that text box.
Source1,Source2. Any suggestion will be helpful.
I think you were too hasty, as your code works on my machine:
<html>
<body>
<input type="text" id="someTxtBox" onkeyup="window.alert(event.keyCode)"/>
<script type='text/javascript'>
function fnGenerateTabKeyEvent() {
var e = document.createEventObject("KeyboardEvent");
e.keyCode = 9; // tab's ASCII
document.getElementById("someTxtBox").fireEvent("onkeyup", e);
}
fnGenerateTabKeyEvent();
</script>
</body>
</html>
There're of course some "issues" (like - accessing elements via getElementsByName, maybe having the script called before the <input>, but let's blame that on copy-pasting ;)) As such, on my IE, running in document mode 8 the alert successfully displays 9.
Is there a way in javascript to detect if a word/string was typed in a textarea? I want to detect the string <svg> being inputed in Ace editor or CodeMirror and then do something else. Sounds like it has been implemented but I don't know how.
It is possible in Javascript to bind to the key up/down/press/etc events on DOM objects. You have to set the appropriate attribute in the HTML.
<textarea onkeyup='checkText(this.value);'></textarea>
This is the key line that calls the Javascript function with the value (text) of the textarea.
Here is a complete example that demonstrates this use. Listening on Key Up is preferred since the new character will be in the text value before the function is called.
<html>
<head>
<script type='text/javascript' >
var oldText = '';
function checkText(text)
{
if(text.length >= 1)
{
if(text == '<svg>' && text != oldText)
{
alert("<svg> found");
}
}
oldText = text;
}
</script>
<body>
<textarea onkeyup='checkText(this.value);'></textarea>
</body>
</html>
I know this is somewhat similar to the others' answers, but it offers an alternative approach:
document.getElementById('textArea').onkeypress = function() {
if(/\<svg\>/i.test(document.getElementById('textArea').value) === true) {
// do whatever you want here
}
}
If you're not familiar with RegExes in JS, they're a great way to find certain strings in things - say, a user's input, like you want. The i flag after the creation ignores the case, just in case you didn't know. Also, putting this script in the head without an onload event or something of the sort won't work - there's nothing for the script to search, since the document hasn't been fully loaded yet.
Hope this helped!
You can compare what is typed with what you expect using the onchange event.
<html>
<script>
function checktext(){
var val = document.getElementById("textbox").value;
// val is what is in the textbox
// compare val here
// for example
if (val == "<svg>"){
alert(val);
}
}
</script>
<body>
<textarea id="textbox" onchange="checktext()"></textarea>
</body>
</html>
In CodeMirror, the "change" event is fired whenever the code changes. You can simply scan the content for the string you are interested in when this fires. Or, if you expect a huge document, and want this to be efficient, you can only scan the changed part of the document (taking care to handle the case where the string is on the boundary of the changed and unchanged parts).
cmInstance.on("change", function(cm) {
if (cm.getValue().indexOf("<svg>") > -1)
doSomething();
});
I am programming a sudoku puzzle (http://www.jsfiddle.net/sZ7Aq/4/). It works okay on IE, but when I try it on Google Chrome, the button doesn't do anything when I click on it. Is there a way to fix it so it works on all browsers?
Please note: I haven't finished it so there isn't a puzzle generating function. You must enter all numbers yourself.
Here is my main() function (if you did not click on the link yet):
function main() {
getcellVal();
if (validate() == false) {
alert("Something's not right!");
return false;
}
alert("Good job!");
return true;
}
My button:
<button onclick="javascript: main()">Check my answer</button>
Use .addEventListener('click', main); For instance:
var check = document.getElementById('check');
check.addEventListener('click', main);
and of course add id="main" and remove the onclick from your button.
Updated fiddle
Then open your console and fix the other bugs...
From your jsfiddle, the error is in your getcellValue() function. This code is incorrect:
colVal = [[x0y0.value, x0y1.value, x0y2.value, x0y3.value, x0y4.value, x0y5.value, x0y6.value, x0y7.value, x0y8.value],
I would suggest you change your input elements to have an id attribute that matches the name. Like this:
<input type="text" name="x0y0" id="x0y0">
Then change your getcellVal() function to use the getElementById function.
colVal = [[document.getElementById("x0y0").value, ...],
It will be much more verbose, but it will work in more browsers.
Few things need to be corrected:
Instead of defining an event such as javascript: main() inline, use unobtrusive solution to register the necessary event handlers programmatically.
Eg:
<button id="buttonid">Check my answer</button>
window.onload = function() {
document.getElementById('buttonid').onclick = main;
};
You cannot access the DOM elements just by specifying their names. In your case x0y0.value will not return anything. Instead use id or class name to access the set of elements.
Eg:
<input type="text" name="x0y0" id="x0y0">
In javascript,
document.getElementById("x0y0").value
Given a keydown event in the browser, how can I predict whether that key event will result in character input? For example, hitting the left arrow doesn't input characters but hitting the a key inputs an A (unless ctrl or alt is down).
I don't need to know what character will be input, just whether the key event will result in an input.
I'm targeting Chrome. Bonus points if your solution works in an IME.
Note: I'm asking about the keydown event, not a downstream event like keypress or oninput.
There's an HTML 5 event: input. MDN: https://developer.mozilla.org/en-US/docs/Web/Reference/Events/input. Other than that there's no proper solution.
Ok, I think I have a solution. I don't know how good it is but it works. Have a look: http://jsfiddle.net/tLPsL/
It's basically saving the value of the input onkeydown and checking it in onkeyup.
$('#sattar').keydown(function() {
window.SATTAR = $(this).val();
});
$('#sattar').keyup(function() {
if(window.SATTAR !== $(this).val()) {
alert("changed");
}
});
[updated]
use this
$(document).keydown(function(event){
console.log(event.which);
});
and filter the value of the event.which according to your needs using the ascii values and exclude the numbers that appear with unwanted buttons
for example (this example demonstrates accepting small letters only):
$(document).keydown(function(event){
var x = event.which;
if (x <= 90 && x >=65) console.log('accepted');
else console.log('not accepted');
});
JSFiddle
[update] :
If you don't like this method you can use another that detects an input to any textfield or textarea :
$('input,textarea').change(function(){
console.log('input detected!');
});
$(document).keyup(function(event){
var x = $(event.target);
if (x[0].nodeName == 'INPUT' || x[0].nodeName == 'TEXTAREA'){ //you can filter the backspace if you don't want to consider it a change on the input by anding it with the whole argument here using the key number explained above
x.blur().focus();
}
});
DEMO
note: The first method works for all languages as the same keyboard keys are used for inputs of different characters but they still can type.
Sources && tips:
I saw the characters keydata list in this site.
-To make it crossplatform and crossbrowser, I suggest you to watch this site
-You can test the keydown event here.
-Jquery also suggest to use key which because it normalizes keycode and charcode (i think this can be usefull for the crossbrowser part but I didn't find a table like the one I posted before for keycode), see details here.
To the end, a personal thought: I wouldn't appear rude by telling this so please, try to understand, you had 3 clear and working answer, should be your interest to improve details to make it working as you need, especially because, for many reason, (like time, hardware disponibility, no one pay us, freelancer site is elsewhere, etc etc), who are helping you, maybe, can't do your entirely work.
EDIT
Considering your needs, I wrote this code, keeps in mind that combination key are hard to handle, so, you should test this example before to re-use it. fiddle
<!DOCTYPE html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$(document).keydown(
function(event){
if(event.target!='[object HTMLBodyElement]'){//Are we in an input?
if(!event.ctrlKey && !event.altKey){//Are we using a combo ctrl or alt?
if(event.keyCode==13 || event.keyCode==8 || event.keyCode==32 || (event.keyCode>45 && event.keyCode<91) || event.keyCode==188 || (event.keyCode>189 && event.keyCode<193) || (event.keyCode>218 && event.keyCode<222)){
//It is a char?
document.getElementById('valid').innerHTML+=event.keyCode+' ';
document.getElementById('idlast').innerHTML=event.target.id;
}
}
}
}
);
</script>
</head>
<body>
<input id="a" type="text"></input>
<textarea id="b">a</textarea>
<div id="c" contenteditable="true">a</div>
<div id="d" style="width:200px;height:200px;background-color:red">a</div>
last keydown in: <span id="idlast"></span><br>
for keypress in input:<span id="valid"></span><br>
</body>
</html>
END EDIT
For first if the focus is on an object that is not an input(textarea,contenteditable...) you are targeting the body. So if the target is the body, for sure you are not writing somewhere.
Then I suggest you to see this example, keypress is probably usefull for your aim, because it seems to don't register keys that aren't an input.
<!DOCTYPE html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$(document).keypress(
function(event){
if(event.target!='[object HTMLBodyElement]'){
document.getElementById('valid').innerHTML=document.getElementById('valid').innerHTML+event.keyCode+' ';
document.getElementById('idlast').innerHTML=event.target.id;
}else{
document.getElementById('out').innerHTML=document.getElementById('out').innerHTML+event.keyCode+' ';
}
}
);
$(document).keydown(function(e){document.getElementById('down').innerHTML=document.getElementById('down').innerHTML+e.keyCode+' ';});
</script>
</head>
<body>
<input id="a" type="text"></input>
<textarea id="b">a</textarea>
<div id="c" contenteditable="true">a</div>
<div id="d" style="width:200px;height:200px;background-color:red">a</div>
last keypress input id: <span id="idlast"></span><br>
for keypress in input:<span id="valid"></span><br>
for keypress out:<span id="out"></span><br>
for keydown:<span id="down"></span><br>
</body>
</html>