Let say in the text input field, I am typing a sentence. Then I input a certain character, for example, "#" like below:
I am writing this example with # symbol.
Using the keypress, when the symbol is used, I want to check the character before and after it.
In this case, it will give two empty spaces.
Another example is:
This is another example using #text.
Here it should give a space as "before" and "t" for "after" the symbol.
How would I detect these characters when keypress condition is met?
Any suggestion will be much appreciated.
Use the input event in conjunction with the selectionStart property on your input element, which allows you to get the position of the cursor.
document.getElementById('example').addEventListener('input', function () {
var text = this.value,
cursor = this.selectionStart
// the characters in question
var previous = text.charAt(cursor - 2),
current = text.charAt(cursor - 1),
next = text.charAt(cursor)
// do something cool
console.log(previous, '|', current, '|', next)
})
<input type="text" id="example" value="edit this example text :)"/>
Related
I'm trying to create a Mask on my input so that the user is forced to enter a value in the format 'YYYY Text' (YYYY being a year but I can not check its validity, I just check that they are numbers). My problem is that it is not working with this regular expression that is good :
var element = document.getElementById('Cline');
var maskOptions = {
mask: /^[0-9]{4} [a-zA-Z]+$/
};
var mask = IMask ( element, maskOptions );
Here is the HTML of my input:
<input type="text" class="field__form-input" id="Cline" name="Cline">
the problem is that for example, the mask works with an expression that I took from the website which is this one:
var element = document.getElementById('Cline');
var maskOptions = {
mask: /^[1-6]\d{0,5}$/
};
var mask = IMask(element, maskOptions);
but when I put the news, the input is blocked and I can no longer write anything in it, as if no character was accepted. And yet the one I put is correct because I tested it without the mask on another input, and there no worries
Make sure that your regular expression accepts any prefix of a valid input, as also the imask documentation highlights.
It is important to realise that the user will enter the input character by character, and at each instance the input should be allowed when it can lead to a valid input when completely entered. Currently that is not the case as your regex requires the 4 digits, the space and at least one letter, which does not allow that the user enters a first digit, and so they cannot enter anything.
So do this:
mask: /^(\d{0,4}|\d{4} [a-zA-Z]*)$/
Snippet:
var element = document.querySelector('input');
var maskOptions = {
mask: /^(\d{0,4}|\d{4} [a-zA-Z]*)$/
};
var mask = IMask(element, maskOptions);
<script src="https://cdnjs.cloudflare.com/ajax/libs/imask/6.4.3/imask.min.js"></script>
<input>
I am creating an input box with an onChange function that will check to see if the characters are only digits and only allow up to one period/dot '.'
The function I have here is not working:
function addPercentSeparator(n) {
let str = n;
let match = str.match(/\d*\.\d*/)
if (match) {
return str;
}
}
I also tried: let match = str.match(/^([0-9]+(\.[0-9]+)?)/)
What I am trying to achieve is only allowing for one period.
If the user enters a number without a period, it will append a period to end of string when they click outside the input box.
This regex is supposed to do the trick:
^\d*\.?\d*$
But if you'll ask me, I would make sure there are digits before the dot, using ^\d+\.?\d*$.
Explanation:
As the dot isn't mandatory, I've added the ?, which symbolizes "0 or 1 occurrences".
I've also added the ^ and the $ to make sure no parts of the string will be matched if the whole string is illegal.
I hope this works for you!
I have an input field in which I want to allow only number and 1 comma. How could I make it accept only single comma?
$("#my-field").on("keyup", checkKey);
function checkKey() {
this.value = this.value.replace(/[^0-9,]/g, "");
}
You could do it like this:
function checkKey() {
var clean = this.value.replace(/[^0-9,]/g, "")
.replace(/(,.*?),(.*,)?/, "$1");
// don't move cursor to end if no change
if (clean !== this.value) this.value = clean;
}
// demo
document.querySelector('input').oninput = checkKey;
<input>
This will remove all repeated commas, and everything between them. That is not an issue, since you press one key at a time.
Remarks
This blocking way of input validation is user unfriendly. It is better to colour things, or put messages, than to make the keyboard disfunctional.
Consider using the <input type="number"> element, which has number validation built in.
The input event is often more useful for checking for changes in the input than keyup, since changes can also be made via mouse actions and the context menu.
If you want to allow dot instead of comma, then change every , with \. in the regular expressions, as . has a special meaning in regular expressions, and must be escaped to be taken as a literal character.
$('#target').val($('#target').val().replace(/[^\d]/g, ""));
I use the above code to leave only numeric characters in an input value I would also like to allow '+' and '-'.
How would I modify the regex to allow this?
Help much appreciated
Put - and + in the character class.
$('#target').val($('#target').val().replace(/[^-+\d]/g, ""));
FWIW I use a couple of input classes that I control with jQuery:
<input class="intgr">
<input class="nmbr">
$("input.intgr").keyup(function (e) { // Filter non-digits from input value.
if (/\D/g.test($(this).val())) $(this).val($(this).val().replace(/\D/g, ''));
});
$("input.nmbr").keyup(function (e) { // Filter non-numeric from input value.
var tVal=$(this).val();
if (tVal!="" && isNaN(tVal)){
tVal=(tVal.substr(0,1).replace(/[^0-9+\.\-]/, '')+tVal.substr(1).replace(/[^0-9\.]/, ''));
var raVal=tVal.split(".")
if(raVal.length>2)
tVal=raVal[0]+"."+raVal.slice(1).join("");
$(this).val(tVal);
}
});
intgr strips all non-numeric
nmbr accepts +, -, . and 0-9. The rest of the string gets stripped of all but 0-9 and the first . If you are OK with the + and - being anywhere, Bamar's solution is perfect, short and sweet. I needed the +/- to be only in the first character position if at all, and only one . (i.e. strip out beyond the first period so 2.5.9 would be 2.59)
In a JavaScript text editor, the total characters accepted per line is 65. I want to change the number of character accepted in a line to 35 with out changing the total character length of my text editor (65).
So, if a user enters 36th character, the cursor should to go the second line although the character length per line is 65. It has to accept only 35 characters per line.
One can only assume your talking about a TEXTAREA html tag, in which case your best bet would be to use a JavaScript regex replace to insert new lines you can attached this to the OnChange event.
edit This JS fiddle seems to work. I used the 'keyup' event instead of 'change'. http://jsfiddle.net/sUS5s/
HTML
<textarea id="demo" rows="5" cols="65"></textarea>
JS
$("#demo").keyup(function(event) {
var txt = $(this).val();
$(this).val(txt.replace(/([^\r\n]{35})/gm, "$1\r"));
});
Simple regex replace with substitution. Matching 35 consecutive NON-newline characters and replacing them with themselves plus a newline.
This will work if you continually type forward, you need something a little more complex to let you insert into previous lines etc without the new lines getting skewed.
EDIT Without jQuery
document.getElementById("demo").onkeyup = function() {
var txt = document.getElementById("demo").value;
document.getElementById("demo").value = txt.replace(/([^\r\n]{35})/gm, "$1\r");
};