Simulate keypress in Javascript not using jquery - javascript

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);
});

Related

How can I re-enable a text field?

I am trying to re-enable a text field that gets automatically filled in and disabled on the website we use for ticketing. It is currently possible to inspect element, and enable manually to field to enter anything you want. I'd like to remove that step. I am trying to make a (very) simple chrome extension that will detect when the field has been disabled and switch it back on, but I'm having no luck.
I've tried several iterations, with no success. Here's what I've got at the
moment.
var subject = document.getElementById('title_fs');
subject.onchange = function() {fix()}
function fix(){
subject.setAttribute("enabled", true)}
I also tried
var subject = document.getElementById('title_fs');
subject.addEventListener("change", {subject.setAttribute("disabled", false)});
The most success I've had so far was accidentally disabling the field as soon as the page loaded. Any suggestions?
Simply remove the attribute
document.getElementById('title_fs').removeAttribute('disabled');
document.getElementById('removeDisabled').addEventListener('click', function() {
document.getElementById('title_fs').removeAttribute('disabled');
});
<textarea disabled="true" id="title_fs">Foobar</textarea>
<button id="removeDisabled">Remove Disabled</button>
element.disabled = true/false
function func() {
var elem = document.getElementById('someId');
elem.disabled = !elem.disabled;
};
<input type="text" id="someId" />
<button onclick="func();">click</button>

How do I force cursor to always be in one form field using HTML5/Javascript?

I am trying to keep the focus always on one form field. It basically needs to always be active on the page so if anything is typed it is always into this field. How do I accomplish this? I have used the autofocus command from HTML5 but once I switch it does not go back without page refresh. Basically I want the cursor to be forced to always stay in that form field?
<input type="text" placeholder="Type Here" id="forced" required autofocus>
This all must be controlled on the client end so only HTML5 and Javascript can be used. Is there a solution for this?
This will do what you're trying to do. I'm listening for the blur event and re-focusing the input when it happens. Here is plain javascript if you don't want the overhead of jQuery for something so simple.
var alwaysFocusedInput = document.getElementById( "focus_target" );
alwaysFocusedInput.addEventListener( "blur", function() {
setTimeout(() =>{
alwaysFocusedInput.focus();
}, 0);
});
<input type="text" id="focus_target" placeholder="always focused" autofocus />
<input type="text" placeholder="some other input" />
You could just stick alwaysFocusedInput.focus(); at the end of your script as #3D1TOR suggested.
Or if you want to support really old Firefox:
Try putting this script I found here at the bottom of your body element for older versions of Firefox.
<script>
if (!("autofocus" in document.createElement("input"))) {
document.getElementById("focus_target").focus();
}
</script>
You could try this..
$("#forced").blur(function(){
$(this).focus();
});
Focus the element when anything that isn't the element is focused.
$(":not('#forced')").focus(function(){
$("#forced").focus();
});
function autoFocus()
{
inputTxt = document.getElementById("forced").autofocus;
}
autoFocus();

Paste event not functioning properly in Opera 11 and lower versions

I am trying out this simple code which is supposed to shift the focus to another text box when a right click is detected on the first, so that any subsequent paste event makes the text to be pasted into the 2nd box:
<!DOCTYPE html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("#real").bind("contextmenu",function() {
$("#paste").focus();
});
});
</script>
</head>
<body>
<input type = 'text' sh = '0' right = '0' id = 'real' />
<input type = 'text' id = 'paste' />
<p>Dummy</p>
</html>
In Opera above versions 12, it is working fine. However, in 11 and below, even though the focus does get shifted to the 2nd text box on right clicking on the first, the paste event pastes the text in the first textbox (with the focus being shifted to the 2nd textbox immediately, on its own). I tried to replace the code by setTimeout(function() { $("#paste").focus(); },0);, still the error persists.
Can anyone tell me how do I fix this, so that the text gets pasted in the 2nd textbox? (Detecting a mouseup, checking whether it's a right click through event.which, if so, shift the focus - yeah, I did that too, same result!)
As an alternative solution...
$("#real").bind("contextmenu",function() {
$("#paste").val($(this).val());
$(this).val('');
});

Looking for ibooks html input alternative

In IOS5 on the iPad, iPad2 etc. iBooks accepted <input type="color"> as a way to prompt the keyboard to display when you clicked on an input field, to say, type in the answer to a question. I've just recently updated to IOS6, and this workaround no longer seems to be working. I tried using the JavaScript I found here - http://www.linkedin.com/groups/How-Show-iPads-Keyboard-when-3877009.S.84287009
<script type="text/javascript">
function iPadTouchHandler(event) {
var type = "",
button = 0; /*left*/
if (event.touches.length > 1)
return;
switch (event.type) {
case "touchstart":
// OLD: On iPad2 clicking on a text input field did not show the keyboard
// if ($(event.changedTouches[0].target).is("select")) {
// NEW: Now on iPad2 the touchstart-Event on input fields is ignored and everything works fine
// change my by Roland Caspers, Scheer Management
if ($(event.changedTouches[0].target).is("select") || $(event.changedTouches[0].target).is("input")) {
return;
}
iPadTouchStart(event); /*We need to trigger two events here to support one touch drag and drop*/
event.preventDefault();
return false;
break;
</script>
However this code seems to be outdated and relevant to IOS5. I know of a workaround, which is to put the page with the input into an iFrame, in that case you can just use <input type="text">, however I'd prefer to stay away from iFrames as they tend to move the content around depending on where the input box is. Any thoughts as to other possible solutions or workarounds? Tyvm :)
I am also Facing the same issue on iOS6 for , the same is working perfectly on the <iframe> tag. But it omits the images & style and etc.
Review the code "http://www.linkedin.com/groups/How-Show-iPads-Keyboard-when-3877009.S.84287009", I feel some thing has to modify on below condition:
($(event.changedTouches[0].target).is("select") || $(event.changedTouches[0].target).is("input"))
I'd be great if anyone provide the earlier response.
Thanks
I struggled with this same problem in iBooks on iOS 7. The tricky part was, that iBooks probably makes all text input fields disabled by default. We are using prototype.js, so here is my solution written for prototype:
$('my-input-field-id').observe('touchstart', function(event) {
var element = event.element();
if (element.disabled)
element.disabled = false;
element.focus();
event.stop();
});
So just listen for the 'touchstart' event on the input field and enable and focus the field when touched. It works for ordinary text fields (<input type="text">). Simple :-).

Making a basic Javascript calculator

jsfiddle demo
Bear with me, total newb here.
I'm trying to make a simple multiplication calculator, as a experimentation with Javascript.
The catch is that -
No libraries, just pure javascript.
Javascript must be unobtrusive.
Now, the problem arises, that it doesn't give the value out.
When I do this locally, answer has a value of NaN, and if you hit Submit it stays that way, BUT, if you press the back button, you see the actual result.
In the JSFiddle, much is not shown, except for the fact that it simply doesn't work.
Please tell me, is it even possible to make an unobtrusive calculator? How?
(PS. I was taking a bit of help from sciencebuddies, just to see basic syntax and stuff, but I found it can't be done without code being obtrusive)
I realize you're probably just getting started and don't know what to include, remove, and whatnot. But, good advice here, clearly label your elements so you can understand them, and pare it down to the smallest possible code you need for it to work (even less, so you can build it up).
Here is your code reworked:
HTML
<div>
<input type="text" id="multiplicand" value="4">
<input type="text" id="multiplier" value="10">
<button type="button" id="multiply">Multiply</button>
</div>
<p id="result">
The product is: <span id="product"> </span>
</p>
Javascript
window.onload = function(){
var button = el('multiply'),
multiplicand = el('multiplicand'),
multiplier = el('multiplier'),
product = el('product');
function el(id) {
return document.getElementById(id);
};
function multiply() {
var x = parseFloat(multiplicand.value) || 0,
y = parseFloat(multiplier.value) || 0;
product.innerHTML = x * y;
}
button.onclick = multiply;
};
http://jsfiddle.net/userdude/EptAN/6/
A slightly more sophisticated approach, with add/subtract/multiply/divide:
http://jsfiddle.net/userdude/EptAN/9/
You have to change the submit button so that it doesn't submit the form. Right now clicking "Submit" causes the form submits to the same page which involves a page reload.
Change the <input type="submit" id="submitt"> to <button type=button> and it should work.
You can probably do without the <form> element in the first place. That'll stop clicking enter in your text input from reloading the page.
Your example has a couple of problems:
The form still submits. After the JS changes the value, the submit will cause the page to reload, and that work you've done setting the answer value is wasted.
You're trying to do this stuff right away. In the header, none of the body has been parsed yet (and thus, the form elements don't even exist). You'll want to wait til the page is loaded.
The script hijacks window.onload. If you don't have any other scripts on the page, that's fine...but the whole point of unobtrusive JS (IMO) is that nothing breaks whether the script is there or not.
Fixed, we have something kinda like:
// Wrap this onload in an IIFE that we pass the old onload to, so we can
// let it run too (rather than just replacing it)
(function(old_onload) {
// attach this code to onload, so it'll run after everything exists
window.onload = function(event) {
// run the previous onload
if (old_onload) old_onload.call(window, event);
document.getElementById('Xintox').onsubmit = function() {
var multiplier = +this.multiplier.value;
var multiplicand = +this.multiplicand.value;
this.answer.value = multiplier * multiplicand;
return false; // keep the form from submitting
};
};​
})(window.onload);
Note i'm attaching the meat code to the form, rather than the button, because hitting Enter in either of the factor boxes will trigger a submit as well. You could still attach to the button if you wanted, and just add a submit handler that returns false. But IMO it's better this way -- that way the form works just the same with JS as without (assuming the script on the server fills in the boxes appropriately), except it won't require a round trip to the server.

Categories