What I am trying to achieve is to force a textbox to start with a prefix ( country telephone code ) and to make this permanent, meaning that the user cannot bypass this. For example, the Phone textbox should always start with "+45" and after that the user can add the phone number. How to prevent it from deleting the code, by any means?
What I done so far, using jQuery:
//attach event on phone text boxes
$(document).delegate(".phone", "keyup", function(event){
var target = $(this);
var value = target.val().trim();
if (value.indexOf(CONSTANTS.DANISH_PHONE_CODE) == -1) {
//country code not found
//if the user starts deleting the country code
if (value.indexOf("+") == 0){
value = "";
}
//if the user types something in front of the country code, put the country code at the end
value = value.replace(CONSTANTS.DANISH_PHONE_CODE, "");
//phone doesn't start with +45
value = CONSTANTS.DANISH_PHONE_CODE + value;
target.val(value);
}
});
But the problem is that the user can delete the plus sign and the prefix is put automatically at the start so we will have +4545. Do you know an elegant way of achieving this? Thanks.
You can absolutely position the text (in a span) over the textbox and add a left-margin to it.
This way users won't be able to remove it. But you'll have to add it server side.
Add the +45 as static html before the field. Required the user to enter "the rest" of the number (not the +45).
If necessary, add the +45 server side before persisting the value. Similarly, remove the +45 when editing.
JSFiddle Example
This should actively keep them from deleting "+45" instead of trying to fix the problem after the user as changed it. Upon keypress, determine character position, if the position is too early in the string (i.e. inside the "+45" as oppose to after it) then don't allow the keypress, unless that key is the left or right arrow keys.
Acquired resources:
http://blog.vishalon.net/index.php/javascript-getting-and-setting-caret-position-in-textarea
Binding arrow keys in JS/jQuery
Related
I was wondering if someone can point me into the right direction. I have a text input field, that I now need to update so a user can only "edit" through a scan gun to capture a bar code. My code so far was updated to prevent the user from adding data via keyboard but I am unsure how I can make it "editable" again via scan. During testing scanning was treated similar to key presses:
$('#barCodeNum').keydown(function(){
$('#barCodeNum').attr('readonly', true);
});
$('#barCodeNum').keyup(function(){
$('#barCodeNum').attr('readonly', true);
alert("You cannot manually edit this field. Please Scan the item.");
});
What event should I be using, if there is any form of an event to capture the "action" of scanning? Or has anyone found another solution to handle this kind of scenario?
EDIT
Another idea... From Anthony's comment about an hidden field...
But! An hidden field just can't be focussed... And you need it to use the codebar reader.
So what about to place that "other" input outside the viewport (using CSS) instead of hiding it... Doing this, no one can focus it and just type in.
So in order to focus it, you will also need an "enable scan" button. The button will also start an interval to check for a value inputed fast! say... within 100ms... Then blur the field.
Here, there's only one delay to handle: The full scan minimum time. So that is easier...
No human can enter a complete code so fast.
Then you just need to validate that the code length is correct, based on your typical codes. If just one or two character are in... It's sure invalid.
You'll have to adjust the "maxScanDelay" by testing your scanner... 100ms may be too short. But make it as short as possible. ;)
Look below:
var ScanCheck;
var maxScanDelay = 100;
$('#barCodeNum').on("keydown",function(e){
e.preventDefault();
}); // End keydown on the visible
$('#barCodeNumHidden').on("input",function(e){
$('#barCodeNum').val($(this).val());
}); // End keydown on the hidden
$("#scanEnable").on("click",function(){
// Clear the fields
$('#barCodeNum,#barCodeNumHidden').val("");
$("#barCodeNumHidden").focus();
$(this).text("Waiting for the code.");
ScanCheck = setInterval(function(){
console.log("interval");
if($('#barCodeNumHidden').val()!=""){
$("#barCodeNumHidden").blur();
$("#scanEnable").text("Enable scan.");
clearInterval(ScanCheck);
console.log("interval stopped");
}
},maxScanDelay);
});
#barCodeNumHidden{
position:fixed;
top:-100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="barCodeNum" readonly>
<input type="text" id="barCodeNumHidden">
<br>
<br>
<button id="scanEnable">Enable scan.</button>
Typing speed solution
If you make it readonly... The codebar reader won't be able to fill the input.
Since just return false; does not work...
I think I found a way to grab the characters typed FAST, like no human can, and get rid of the character typed more slowly.
I have no codebar reader to test that...
You will have two delays to adjust :
A threshold (key must be typed faster than this delay)
An "output" delay (to allow all characters to be collected before an output)
Here the code to try:
var string = "";
var timeout;
var lastEventTime = 0;
// ADJUST THOSE TWO!
var threshold = 35;
var outputDelay = 100;
$('#barCodeNum').on("keydown",function(e){
e.preventDefault();
var codebarInput = $(this);
// Get current time.
var thisEventTime = Date.now();
console.log(lastEventTime);
console.log(thisEventTime);
// Grab the character.
string += String.fromCharCode(e.keyCode)
console.log(string);
// If this event occurs sooner than the threshold delay, use the timeout to output the value when all characters are in string.
if(lastEventTime+threshold > thisEventTime){
console.log("OK");
// Output the string after a delay.
clearTimeout(timeout);
timeout = setTimeout(function(){
codebarInput.val(string);
},outputDelay);
// If this event occurs after the threshold delay, clear string and input value.
}else{
console.log("NOT OK");
codebarInput.val("");
string = "";
console.log("Key prevented.");
}
// Keep this event time.
lastEventTime = thisEventTime;
}); // End keydown
From my tests on CodePen, a HOLDED down key works with a 35ms threshold... That seems to be the lowest, since 30ms block everything. With this threshold, even if I type as fast as I can, no single keys are passing. ;)
Usually barcode scanners act as a keyboard input, which would prevent you from knowing whether its a keyboard or a scanner.
One way to get around this is to check the timing between keypresses. The barcode scanner inputs much faster than a human, and I believe you can modify this speed.
If the typing is slow enough you'll know its a keyboard. If the typing is within some threshold you will know its the scanner.
I have a <input id="inp" type="text"> that user writes in, and sometimes uses suggests from a dictionary. When a suggest is selected I do:
var input = $('#inp');
input.val(input.val()+suggestedText+' ');
input.focus(); // that is because the suggest can be selected with mouse
everything works great, but when after adding a suggest that makes the resulting input.val() too long to fit in the edit field, the cursor is at the end of the string (which is good), but only the beginning of the string is visible in the edit field, so the cursor is hidden as well.
As soon as a key is pressed (a key that changes the value) the "scroll" goes to the end of the string hiding the beginning... How to trigger this behavior automatically, without having to press a key?
I have found a solution here - but it is not good as the whole input experience is changed...
Have you tried:
var input = $('#inp');
input.val(input.val()+suggestedText+' ');
input.focus(); // that is because the suggest can be selected with mouse
var height=input.contents()[0].outerHeight()
input.animate({
scrollTop:height
},'normal');
?
thank you all for answers, meanwhile I have found sth as well...
when using mouse to click the input lost focus (clik on sth else), and then regained it (thanks to input.focus()) - "scrolling" to the end, but when choosing a suggest was done with a keyboard, focus was never lost, and that is why it was not "scrolling" itself. I just simply added input.blur(), before input.focus(), now works like a charm... have a look at working example
http://46.4.128.78/input/
To make this work you need to set the focus() BEFORE you set the value. You can fix this in many ways, for example:
input.focus(); // that is because the suggest can be selected with mouse
var input = $('#inp');
input.val(input.val() + suggestedText + ' ');
Or this one:
function changeValue(element, newValue) {
element.focus();
element.val(element.val() + newValue + ' ');
}
Im just wondering how I go about catching the event when the user is typing into a text input field on my web application.
Scenario is, I have a contacts listing grid. At the top of the form the user can type the name of the contact they are trying to find. Once there is more than 1 character in the text input I want to start searching for contacts in the system which contain those characters entered by the user. As they keep typing the data changes.
All it is really is a simple type ahead type functionality (or autocomplete) but I want to fire off data in a different control.
I can get the text out of the input once the input has lost focus fine, but this doesnt fit the situation.
Any ideas?
Thanks
Use the keyup event to capture the value as the user types, and do whatever it is you do to search for that value :
$('input').on('keyup', function() {
if (this.value.length > 1) {
// do search for this.value here
}
});
Another option would be the input event, that catches any input, from keys, pasting etc.
Why not use the HTML oninput event?
<input type="text" oninput="searchContacts()">
I would use the 'input' and 'propertychange' events. They fire on cut and paste via the mouse as well.
Also, consider debouncing your event handler so that fast typists are not penalized by many DOM refreshes.
see my try:
you should put .combo after every .input classes.
.input is a textbox and .combo is a div
$(".input").keyup(function(){
var val = this.value;
if (val.length > 1) {
//you search method...
}
if (data) $(this).next(".combo").html(data).fadeIn(); else $(this).next(".combo").hide().html("");
});
$(".input").blur(function(){
$(this).next(".combo").hide();
});
Basically I need to create a textarea that is character limited, but will have a single word at the beginning, that they can't change.
It needs to be a part of the textarea, but I don't want users to be able to remove it or edit it.
I was thinking I could create a JQuery function using blur() to prevent the user from backspacing, but I also need to prevent them from selecting that word and deleting it.
UPDATE
I wrote this JQuery which seems to work great! However I like the solution below as it requires no Javascript.
<script type="text/javascript">
var $el = $("textarea#message_create_body");
$el.data('oldVal', $el.val());
$el.bind('keydown keyup keypress', function () {
var header = "Header: ";
var $this = $(this);
$this.data('newVal', $this.val());
var newValue = $this.data("newVal");
var oldValue = $this.data("oldVal");
// Check to make sure header not removed
if (!(newValue.substr(0, header.length) === header)) {
$(this).val(oldValue);
} else {
$(this).data('oldVal', $(this).val());
}
});
</script>
If you just want the textarea to show a prefix, you can use a label, change the position, and indent the textarea content. User will not notice the difference.
You can see how it works here: http://jsfiddle.net/FLEA3/.
How about just putting this word as a label next to the textbox? It may be confusing for the users not to be able to edit part of the text in the textbox.
Wouldn't it be better if you just alert the user that whatever he inputs in the textarea will be submitted with a "prefix" and then
show the prefix as a label before the textarea
add the prefix to the inputted text before submitting
I need some kind of textbox control that can host buttons along the text strings. Basically I want to create a textbox with names that enables the user to remove some names after addition. How can this be accomplished in javascript ?
Thanks in advance.
Just add SPANs before the textbox in your element. Format the SPANs as colored boxes with the text and maybe an X for deleting the entry and you're good to go.
Using JQuery this is really easy. Or do you want a Webforms-Control which is able to do that?
Edit:/
The Inline-Element could look like that:
<span id="my-filterbox">
<input type="text" name="next-filter" />
</span>
And then your JS to add a key-event handler. Im using JQuery in this case:
$('#my-filterbox').keyup(function(event) {
if(event.keyCode == '13') { // 13 = key code for enter
var value = $(this).val();
$(this).val('');
$('#my-filterbox').prepend('<span class="filter-elem">' + value + '</span>');
}
});
This way you add the filter to the span my-filterbox everytime the user hits enter. Per CSS you're able to format the span at the left side of the input box.
This code is untested but I think you get the idea.