I've looked around for ages trying to figure out this, hope you can help me.
Basically I have a feature on my site where the user can post a question. Essentially I want a permanent question mark at the end of what they're typing. The question mark is already added in the back end so this is strictly a visual problem.
The question mark moves up when they type.
I can't attach a photo but you can imaging :
The user typing here and after the type line there's a trailing question mark (type line-->)|?
Thanks in advance!!
You could do this :
$('#a').keyup(function(){
var v = this.value.replace(/\?/g, '') + '?';
if (this.value != v) this.value = v;
});
Demonstration
But users don't really like when the content of the input changes of its own. I'd avoid this if possible.
This second version puts a space before the ? :
$('#a').keyup(function(){
var v = this.value.replace(/ ?\?/g, '') + ' ?';
if (this.value != v) this.value = v;
});
Demonstration
Use a little javascript.
Attach an event onto the onkeyup event of the tickbox, and whenever it fires, check to see if the contents end with a question mark. If it doesn't, then add it!
Personally though, it would annoy me, as a user-I'd prefer to only see the question mark once I'be submitted.
I would perhaps instead recommend that you do a check on the server to see if the question contains a question mark (or multiple) at the end, then replace/add the single question mark.
As stated already, it's not really friendly to force a certain input - do the proper checks yourself and take the burden off the user.
If the goal is simply visual reinforcement, then it might be easiest to put a text or graphical question mark outside the text input, possibly in an interesting color, like bold green.
You don't really want to be trying to manipulate the input as the user is typing; you will likely always run into edge cases where the content gets mangled. If it's purely for presentational purposes, just add a ? character just after the input; if you surround it with something like a span, you can target it with CSS to adjust its size or font weight to make it more obvious:
.jumbo
{
font-size: 2em;
}
<input /><span class="jumbo">?</span>
An alternate solution (but overkill if you aren't already using it) is to use an icon font like FontAwesome and add, say, the question-mark icon: http://fortawesome.github.io/Font-Awesome/icon/question/
<input /><i class="icon-question icon-large"></i>
you can put the editable text inside a contenteditable span followed by another span that has the non editable question mark.
http://jsfiddle.net/Paawn/1/
<div class="box">
<span contenteditable="true">This is content i can edit</span>
<span class="question-mark">?</span>
</div>
Here's a pretty decent solution built off of ideas above and elsewhere on stack overflow. Using jQuery
Just add the following snippet and then add the class questionableInput to your input
<input id="yourInput" type="text" name="theInput" class="questionableInput"/>
(function($) {
$.fn.getCursorPosition = function() {
var input = this.get(0);
if (!input) return; // No (input) element found
if ('selectionStart' in input) {
// Standard-compliant browsers
return input.selectionStart;
}
}
$.fn.setCursorPosition = function(pos) {
var input = this.get(0);
if (!input) return; // No (input) element found
if ('selectionStart' in input) {
// Standard-compliant browsers
input.selectionStart = pos;
input.selectionEnd = pos;
}
}
$(".questionableInput").keyup(function(e) {
if (e.keyCode == 37 || e.keyCode == 38 || e.keyCode == 39 || e.keyCode == 40 || e.keyCode == 13
|| e.keyCode == 8 || e.keyCode == 17 || e.keyCode == 16 || e.keyCode == 36 || e.keyCode == 63
|| e.keyCode == 35 || e.ctrlKey) {
return;
}
var positionBeforeMessingWithIt = $(this).getCursorPosition();
if (this.value.slice(-1)!='?') this.value += '?';
if (this.value.slice(-2)=="??") this.value = this.value.substring(0, this.value.length - 1);
$(this).setCursorPosition(positionBeforeMessingWithIt);
});
})(jQuery);
http://jsfiddle.net/YpEgN/2/
Related
I already have a series of events of keypress to trigger some sound, to run countdown clock and whatnot.
I also want to assign keycode to change the value of a couple of input[type=number], either subtract or add value by incremental of -1/+1 each key press. I have done some search but couldn't really give me the ultimate guide.
Here's what I have in the header.
function runScript(e){
if(e.keyCode == 32 && e.shiftKey){
gameclock();
}}
and on my html
<body onkeydown="runScript(event)">
...
<input id="whateverID1" type="number" value="00">
Let's say if I want to add #whateverID1 value by pressing = and subtract #whateverID1 value by pressing -, appreciate any guide to how can I achieve that. Thank you very much.
I have tried this but doesn't seem to work.
var CounterName = 0;
if(e.keyCode == 49 ) {
document.getElementById('whateverID1').value = ++CounterName;
}
if(e.keyCode == 50 ) {
document.getElementById('whateverID1').value = --CounterName;
}
For one, using onclick/onkeydown things in html is usually bad practice. Rather, give the element an id or class and add an eventListener from the JS instead.
Try this below, the jsfiddle is working and should let you do what you want:
document.getElementById("bodyId").addEventListener("keydown", function (event) {
var CounterName = 1;
var currentValue = parseInt(document.getElementById('whateverID1').value);
if(event.keyCode == 187) {
document.getElementById('whateverID1').value = currentValue + CounterName;
}
else if(event.keyCode == 189) {
document.getElementById('whateverID1').value = currentValue - CounterName;
}
});
http://jsfiddle.net/Maxmaxs5/7thqo0zs/7/
If this helps or you need anything else, let me know!
I have the following problem, I need to change the input on a textfield to uppercase, but I can't use css nor the usual way where you see the input changing to uppercase. The input has to appear in capitals from the beginning, I'm trying to find a way to do this but I need some help.
I've done this but it doesn't work, the idea was to change the noncapital input to capital using a KeyboardEvent:
<s:textfield id="textfield1" />
$("#textfield1").keypress(function(event) {
var isMinus = (event.keyCode >= 97) && (event.keyCode <= 122);
if(isMinus) {
var evento = document.createEvent("KeyboardEvent");
evento.initKeyboardEvent("onkeypress", true, true, window, event.keyCode - 32, event.location, "", event.repeat, event.locale);
event.currentTarget.dispatchEvent(evento);
}
});
Any tips? Thanks for reading!
You can try this:
$("#textfield1").keypress(function(event) {
var isMinus = (event.keyCode >= 97) && (event.keyCode <= 122);
if (isMinus) {
var letra = String.fromCharCode(event.keyCode-32);
this.value+= letra;
event.preventDefault();
event.stopPropagation();
}
});
Example: http://jsfiddle.net/kx23u3z1/
:)
You need to change it to id="textfield1"
Also, see my answer here for more on the topic: Allow text box only for letters using jQuery?
TL;DR - don't change the input unless the user has done something wrong, or you'll adjust the cursor position and frustrate the user.
My Requirement is to validate the ip ranges, I need to create a JavaScript function to accept only numeric and it must allow only between the range 0 to 255. If anything is entered beyond that it must alert a message.
I am currently using this below function
<script language="JavaScript">
function allownums(a)
{
if(a <48 ||a > 57)
alert("invalid")
else
alert("vaild")
}
</script>
<input type='text' id='numonly' onkeypress='allownums(event.keycode)'>
I am new to JavaScript, Need some experts suggestion to fix my requirement. Please suggest me
Thanks
Sudhir
Currently you have the test
(a < 48) || (a > 57)
for invalid values. So I would change those:
(a < 0 ) || (a > 255)
You may also need to consider what you'll do with non-integral input like 2.3 - either round it or treat it as invalid.
At present, as Kelvin Mackay points out, you are performing the validation on the keypress event rather than the input value, so change the onkeypress to allownums(this.value).
I would advise changing the alert to a warning in a div, and using the validation to enable/disable a submit button, as popups are quite annoying in just about every circumstance.
To clear the input when an invalid entry is made (as requested in a comment) would make it rather annoying for the user; as soon as a key is pressed to add a digit and make the input invalid, the whole input is cleared. The code, however, would be:
if(!validnum(this.value))
this.value="";
in the input tag, thus:
<input type='text' id='numonly'
onkeyup='if(!validnum(this.value)) this.value="";'>
with the function changed to:
function validnum(a) {
if(a < 0 || a > 255)
return false;
else
return true;
}
or more succinctly:
function validnum(a) {
return ((a >= 0) && (a <= 255));
}
Edit: To alert and clear the box, if you must:
function validOrPunchTheUser(inputElement) {
if(!validnum(inputElement.value)) {
window.alert('badness'); // punch the user
inputElement.value = ""; // take away their things
}
}
<input type='text' id='numonly'
onkeyup='validOrPunchTheUser(this)'>
However, reading other answers, apparently you are looking to validate an octet (e.g. in an IP address). If so, please state that in the question, as it passed me by today. For an octet:
function validateIPKeyPress(event) {
var key = event.keyCode;
var currentvalue = event.target.value;
if(key < 96 || key > 105)
{
event.preventDefault();
window.alert('pain');
return false;
}
else if(currentvalue.length > 2 ||
(currentvalue.length == 2 &&
key > 101)) {
window.alert('of death');
event.preventDefault();
event.target.value = event.target.value.substring(0,2);
}
else
return true;
}
With the input tag:
<input type='text' id='octet'
onkeydown='validateIPKeyPress(event)'>
Except please don't use alerts. If you take out the alert lines, it will silently prevent invalid inputs. Note the change to use onkeydown now, so that we can catch invalid key presses and prevent the value changing at all. If you must clear the input, then do if(!validateIPKeyPress(event)) this.value = "";.
I would rather go instantly for validation of whole ip address. Allowing input both numbers and dots, parsing them thru REGEX pattern.
Pattern usage example you could fetch here:
http://www.darian-brown.com/validate-ip-addresses-javascript-and-php-example/
The code itself would look something like:
<input type='text' id='numonly' value="" onkeypress='allowIp(event)' onkeyup='javascript:checkIp()'>
function allowIp(e){
if((e.keyCode < 48 || e.keyCode > 57) && e.keyCode != 46) // both nubmer range and period allowed, otherwise prevent.
{
e.preventDefault();
}
}
function checkIp()
{
var ip = $("#numonly").val();
/* The regular expression pattern */
var pattern = new RegExp("^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.)(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.)(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.)([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$");
/* use javascript's test() function to execute the regular expression and then store the result - which is either true or false */
var bValidIP = pattern.test(ip);
if(bValidIP){
// IP has ok pattern
$("#numonly").css("background", "green");
}
else {
$("#numonly").css("background", "red");
}
}
You could check it here on fiddle
http://jsfiddle.net/Indias/P3Uwg/
Single Integer
You can use the following solution to check if the user input for a single integer is between 0 - 255:
document.getElementById('example').addEventListener('input', event => {
const input = event.target.value;
console.log(/^\d+$/.test(input) && input > -1 && input < 256);
});
<input id="example" type="text" placeholder="Enter single integer" />
IP Address
Alternatively, you can use the code below to verify that each section of an IP address is between 0 - 255:
document.getElementById('example').addEventListener('input', event => {
const input = event.target.value;
console.log(input === new Uint8ClampedArray(input.split('.')).join('.'));
});
<input id="example" type="text" placeholder="Enter IP address" />
You need to validate the current value of the input, rather than the last key that was pressed:
<input type='text' id='numonly' onkeypress='allownums(this.value)'>
Your function then just needs to be modified to: if(a < 0 || a > 255)
A function like this should do it:
function allownums(value){
var num = parseInt(value,10);
if(num <0 || num>255)
alert('invalid')
}
Then have your html look like:
<input type='text' id='numonly' onblur='allownums(this.value)'>
Live example: http://jsfiddle.net/USL3E/
Update
I've set up a fiddle that does some basic IP-formatting and checks weather or not all input is in range (0 - 255) etc... feel free to use it, improve it, study it... I've also updated the code snippet here to match the fiddle
There are several things you're not taking into account. First and foremost is that not all browsers have a keycode property set on the event objects. You're better off passing the entire event object to the function, and deal with X-browser issues there. Secondly, you're checking key after key, but at no point are you checking the actual value that your input field is getting. There are a few more things, like the use of the onkeypress html attribute (which I don't really like to see used), and the undefined return value, but that would take us a little too far... here's what I suggest - HTML:
<input type='text' id='numonly' onkeypress='allowNums(event)'>
JS:
function allowNums(e)
{
var key = e.keycode || e.which;//X-browser
var allow = '.0123456789';//string the allowed chars:
var matches,element = e.target || e.srcElement;
if (String.fromCharCode(key).length === 0)
{
return e;
}
if (allow.indexOf(String.fromCharCode(key)) === 0)
{//dot
element.value = element.value.replace(/[0-9]+$/,function(group)
{
return ('000' + group).substr(-3);
});
return e;
}
if (allow.indexOf(String.fromCharCode(key)) > -1)
{
matches = (element.value.replace(/\./g) + String.fromCharCode(key)).match(/[0-9]{1,3}/g);
if (+(matches[matches.length -1]) <= 255)
{
element.value = matches.join('.');
}
}
e.returnValue = false;
e.cancelBubble = true;
if (e.preventDefault)
{
e.preventDefault();
e.stopPropagation();
}
}
Now this code still needs a lot of work, this is just to get you going, and hopefully encourage you to look into the event object, how JS event handlers work and all the rest. BTW, since you're new to JS, this site is worth a bookmark
function fun_key()
{
var key=event.keyCode;
if(key>=48 && key<=57)
{
return true;
}
else
{
return false;
alert("please enter only number");
}
}
and you can call this function on keypress event like:
<asp:textbox id="txtphonenumber" runat="server" onkeypress="return fun_key()"> </asp"textbox>
I've seen many answers that have overlooked two important factors that may fail to validate range number on keypress:
When the value in input textbox is NOT SELECTED, the real outcome should be (input.value * 10) + parseInt(e.key) and not simply input.value + parseInt(e.key). It should be * 10 because you add one more digit at the back during keypress, e.g. 10 becomes 109.
When the value in input textbox IS SELECTED, you can simply check if Number.isInteger(parseInt(e.key)) because when 255 is selected, pressing 9 will not turn into 2559 but 9 instead.
So first of all, write a simple function that check if the input value is selected by the user:
function isTextSelected (input) {
if (!input instanceof HTMLInputElement) {
throw new Error("Invalid argument type: 'input'. Object type must be HTMLInputElement.");
};
return document.getSelection().toString() != "" && input === document.activeElement;
}
Next, this will be your on keypress event handler that takes into consideration of the above two factors:
$("input[type='number']").on("keypress", function (e) {
if (!Number.isInteger(parseInt(e.key)) || (($(this).val() * 10) + parseInt(e.key) > 255
&& !isTextSelected($(this)[0]))) {
e.preventDefault();
};
});
Take note of this condition within another brackets, it is one whole condition by itself:
(($(this).val() * 10) + parseInt(e.key) > 255 && !isTextSelected($(this)[0]))
For the < 0 condition, you don't even need it here because the negative sign (-) will be automatically prevented as the sign itself is not an integer.
KNOWN ISSUE: The above solution, however, does not solve the situation when the user move the cursor to the start position of 29 and press 1, which will become 129. This is because 29 * 10 = 290, which already exceed 255, preventing user from entering 129, which is valid. The start position is particularly hard to track when the input type="number". But it should be enough to resolve the normal way of input for an integer range field. Any other better solutions are welcome.
I created this fiddle that the div value changes based on your dropdown list selection. http://jsfiddle.net/qSkZW/20/
I want to take it one step further and this is to create a textbox field that if you add for example the number 2 it will change the div value to 240 (in real the 120 you find in the script it will be a php var). If it writes 3 then to 360.
Additionally there must be two limitations.
Prevent them from using non-numeric characters.
The maximum number is pre-configured (from a php variable). Like if the max value is set to 10, if the user writes 30 it will return to 10.
Thank you for your help.
Okay, so first, create a textfield (example id="textfield"), then modify your listener's action to
$("#quantity").change(function () {
var price = parseInt($(this).val(), 10)*120
$("#textfield").attr('value="'+price+'"');
# sets the default value of #textfield to the selection from #quantity
})
.change()
$("#textfield").blur(function () {
# when the element looses focus (they click/tab somewhere else)
var valid = /^\d{2}$/;
# this means any 2 numbers. change {2} to {3} or however many digits.
# you can also also use d[0-10] to identify a range of numbers.
if ( $(this).text() != valid ) {
$("#message").text("Only numbers please!");
$("#message").fadeIn();
# add <span id="message" style="display:none;"></span> next to #textfield
# enclose #textfield & #message in the same element (like <li> or <div>)
}
else {
$("#message").fadeOut();
}
});
Could you please provide more info about #2 (I don't have a clear understanding of what is supposed to happen)
Quick question: why are you trying to put a price in an editable element?
This will do it: http://jsfiddle.net/ebiewener/pBeM8/
You bind the keydown event to the input box in order to prevent the undesired characters from being entered, and bind the keyup event in order check the value & modify the div's height.
$('input').keydown(function(e){
if(!(e.which >= 48 && e.which <=58) && e.which !== 8 && e.which !== 46 && e.which !== 37 && e.which !== 39){ //prevent anything other than numeric characters, backspace, delete, and left & right arrows
return false;
}
})
.keyup(function(){
val = $(this).val();
if(val > 10){
val = 10;
$(this).val(10);
}
$('div').height(val * 10);
});
var max = 30;
$('input').keyup(function() {
var v = $(this).val();
v = isNaN(v)?'':v;
v = v > max ? max : v;
$(this).val(v);
$('div').html(v * 120);
});
http://jsfiddle.net/vWf2x/2/
Is it possible to change the character which has been entered on keypress, without doing it manually?
For example, if I want to force uppercase letters based on some condition, it'd be nice to do the following:
function onKeypressHandler(e)
{
if ( condition )
{
e.which -= 32;
}
}
But of course that doesn't work.
NOTE: This is not an across the board uppercasing, but only specific characters.
Maybe I want to say if ( e.which >= 97 && e.which <= 102 ) or if ( Wind.Direction == 'South' ) or whatever - the condition itself is not important, but the uppercasing must only apply to the current character not the entire input.
I can do it by manually appending the changed character, but this is an ugly and messy way of doing it, and probably slower than it could be.
function onKeypressHandler(e)
{
if ( condition )
{
$j(this).val( $j(this).val() + String.fromCharCode( e.which - 32 ) );
return false;
}
}
A specific flaw with this method - if selecting all input text and entering a key, if it drops into this then it doesn't remove existing content, but simply appends to the content the user wanted removed. (Would need to investigating detecting any selected text to solve that, which makes this one even uglier.)
Can anyone provide a better solution?
The following will do the job. It's based on an answer I wrote to another question. Customize the transformTypedChar function to suit your needs; my example capitalizes only the letters a-g.
If you need this on a textarea rather than an <input type="text"> then be aware that there are issues in IE <= 8 with line breaks that the following code doesn't handle for the sake of brevity. You can find the cross browser function for obtaining the selection within a textarea here: Is there an Internet Explorer approved substitute for selectionStart and selectionEnd?
function transformTypedChar(charStr) {
return /[a-g]/.test(charStr) ? charStr.toUpperCase() : charStr;
}
document.getElementById("your_input_id").onkeypress = function(evt) {
var val = this.value;
evt = evt || window.event;
// Ensure we only handle printable keys, excluding enter and space
var charCode = typeof evt.which == "number" ? evt.which : evt.keyCode;
if (charCode && charCode > 32) {
var keyChar = String.fromCharCode(charCode);
// Transform typed character
var mappedChar = transformTypedChar(keyChar);
var start, end;
if (typeof this.selectionStart == "number" && typeof this.selectionEnd == "number") {
// Non-IE browsers and IE 9
start = this.selectionStart;
end = this.selectionEnd;
this.value = val.slice(0, start) + mappedChar + val.slice(end);
// Move the caret
this.selectionStart = this.selectionEnd = start + 1;
} else if (document.selection && document.selection.createRange) {
// For IE up to version 8
var selectionRange = document.selection.createRange();
var textInputRange = this.createTextRange();
var precedingRange = this.createTextRange();
var bookmark = selectionRange.getBookmark();
textInputRange.moveToBookmark(bookmark);
precedingRange.setEndPoint("EndToStart", textInputRange);
start = precedingRange.text.length;
end = start + selectionRange.text.length;
this.value = val.slice(0, start) + mappedChar + val.slice(end);
start++;
// Move the caret
textInputRange = this.createTextRange();
textInputRange.collapse(true);
textInputRange.move("character", start - (this.value.slice(0, start).split("\r\n").length - 1));
textInputRange.select();
}
return false;
}
};
How about preventing default action and then triggering the keypress? Something like,
function onKeypressHandler(e)
{
if ( condition )
{
e.preventDefault();
// create new event object (you may clone current e)
var ne = new jQuery.Event("keypress");
ne.which = e.which - 32;
$(e.target).trigger(ne); // you may have to invoke with setTimeout
}
}
You've got to see this.. I was pretty happy with myself after getting it to work..
You obviously would want to include sufficient criteria to avoid going into a loop here.
The code below returns false when condition evaluates to true, but it fires the same event with a different charCode which will not return false.
document.getElementById("input1").onkeypress = Handler;
function Handler(e)
{
e = e || window.event;
if ( e.charCode == 97 )
{
var evt = document.createEvent("KeyboardEvent");
evt.initKeyEvent("keypress",true, true, window, false, false,false, false, 0, e.charCode -32);
this.dispatchEvent(evt);
return false;
}
return true;
}
you could use fireEvent in IE...
I used
http://help.dottoro.com/ljrinokx.php
and
https://developer.mozilla.org/en/DOM/event.initKeyEvent for reference
Not really sure what you want but will this work?
$('#my_element').keyup(function(){ $(this).val().toUpperCase(); });
or use a sub string to get the last character pressed and do toUpperCase() on that?
(psst... you can use keydown or keypress too).
Can you use css?
<input type="text" style="text-transform: uppercase;" />
Peter,
You might find some inspiration here:
http://www.maconstateit.net/tutorials/JSDHTML/JSDHTML15/jsdhtml15-05.htm
basically walks around the various ways to look at the keypress events and functions around that 'area'.