Detecting each character inputed in field and run conditionals - javascript

I am building a web app. I believe it will be easiest if I try to explain what I want the user experience to look like before I ask my question.
I want my user to go on my site and begin to type in a text field. When each character is inputted, I want to run a conditional statement on that character to decided if it should be added to the text field. If the character inputted is not one I want, the character isn't added.
I have validations in my model to do this after the text is submited, but I want it to be real time. I'm guessing this relates to JavaScript and I am not comfortable enough in coding it to know what to search for/research. Can you assist me in where to look (Tutorials, Concepts, etc)?
Thank you for taking the time to read this.

You can do this with the preventDefault method on the event object passed to the keydown event. This basically tells the browser to not preform its default action (which on a text field would be appending the letter to the field).
Here is an implementation using jQuery for brevity, but you can implement the same functionality in pure javascript as well:
$('input').on('keydown', function(event) {
// event.which is the character code
if ( /* some condition */ ) event.preventDefault();
});
And here is a fiddle with an example where you cannot type the letter A: http://jsfiddle.net/354XJ/

It's not precisely your situation but a very good starting point would be this question and its answers: How to allow only numeric (0-9) in HTML inputbox using jQuery?
You are basically looking for javascript that will intercept the keypress and only allow it if it is an allowed key, the question above implements this for numeric keys - start with that and expand it as per your needs.

Related

TinyMCE Autocomplete Without Trigger Character, like gmail

I'm looking for a way to implement an autocomplete function of some sorts in TinyMCE that does not require a trigger character or shows a list of matches, but in stead suggests the continuation of a sentence like gmail does when you write an email.
(the rest of the sentence is suggested by the application)
In stead of the trigger character, the string to match will have to be for example the last few words typed, or the current sentence so far.
I have the backend to provide the actual suggestion based on a partial sentence but I can not find a way to implement this client side anywhere in the documentation. The only post on stackoverflow that looked relevant did not have the answer.
It does not work to simply not provide any trigger character, and it is also not possible to use a space bar / whitespace as the trigger character. Even if you could, it still needs to query the document for the querystring to send to my backend, not just the characters followed by a trigger character.
Should I not be using the autocomplete functionality for this? Is there a better way? How do I go about doing this?
https://fiddle.tiny.cloud/u7haab/12

Show suggestions from when user types a specified character in textbox

Problem Statement: Using javascript or Jquery, I want to build this functionality where if user types a specified character in a textbox, say # symbol, then values of an array should be displayed in drop down. say for example I have array with values:
values[ yyyy,yy]
when User types: abc#
then after # yyyy and yy should appear in drop down.
It is like when we write # symbol in whatsapp group it shows the list of contacts of that group. this functionality is similar to that.
Also, it is different from normal autosuggest which shows suggestions when user types something.It is different from jquery autocomplete functionality, where suggestion is shown based on the input present in the text box. Here we want values of a predefined list in drop down, the moment a user types # symbol and not on the basis of whole input in the textbox.
Experts please help to achieve this.
Basic Implementation:
You can attach a listener on the keypress in the input / some specific element (Could also be a contenteditable div)
and then you can check if the user has pressed the # key or not.
let element = document.getElementById('#some-element');
element.addEventListener('keydown', function(event) {
const key = event.key;
if (key === '#') {
displaySuggestions();
}
});
As soon as the user presses the '#' key, you can call the displaySuggestions() functions.
It'll be a simple component which you can build and when the user clicks on any of the value in the suggestion, you can insert that value at the caret position.
Refer the following: Insert text into textarea at cursor position (Javascript)
There are many libraries out there which nicely provide this functionality, you may want to check them out.
Update:
I made a small project on codesandbox and you can click on the following link to check it out:
This will help with a starting point.
I have documented the code explaining the behavior and how it's being done.
In the example I have used a contenteditable div and definitely the example is not optimized for performance but a lot of things can be done around it to improve it.
I agree there are tons of bugs and all of these can be sorted out but in 20-30 minutes, that's all I could do.
To sum it up:
You can take inspiration from this or continue editing this or come up with a better solution of yours.
Other people might be having great solutions to this and I look forward to them.
May the Power of Javascript be with you.
Here's the project in action:

Reliable html5 input type handling

I know there is a pattern a attribute for html5 input tag, but this help to validate the field after the user has entered the value.
The request here is to prevent the user to type something wrong, instead of correct it after. I'm not interested to discuss if it's better or not - it's just the request.
I also know I could add an event listener for keyPress event and decide which chars accept.
But all the examples I saw are not cross-browser compatible (I'm interested at least in FF, Chrome, in both desktop and mobile versions) and they fails because the user can enter "----" or "....".
What could be a reliable, robust, cross-browser regexp pattern to allow the user to type:
any number [0..9]
only one decimal point ('.' or ',' converter to the first one)
a specified number of decimals (i.e. numbers after the decimal point)
optional only one sign symbol ('+' or '-') as first char
common text commands: arrow keys, copy/cut/paste, backspace, delete, enter
It's better without the use of jQuery - because I should add it only for this goal.
"The request here is to prevent the user" -- don't do that.
If I am typing my name, but my finger slips when typing the i and I hit the 8 key too... no big deal, I just hit backspace, right?
Well, with your idea, wrong. Your name input would disallow numbers, so the accidental 8 wouldn't appear, and the backspace would erase the i instead.
In your question you appear to be seeking a numeric input (have you considered <input type="number" />?) so the finger-slip could apply to the * key when trying to input a 9. Whatever your input the same idea applies.
Always allow the user to type whatever they want. When they are done typing (either onchange of the element or onsubmit of the form), then you tell them "hey, this thing you typed doesn't seem right."
Therefore, the behaviour provided by browsers supporting input[pattern] is correct, and should not be changed.

Jquery Validation restrict characters on live?

Is there a way to block or restrict special characters from input fields with jquery-validation?
For example, I would like to only authorize those characters [0-9\/]*.
I've read the whole documentation but I haven't found anything. So instead I've to write special codes for this which is not a good choice for the code.
I've seen that other javascript plugin validation can do that like Parsley by using a requirementType. But I don't really want to change the plugin to another cause I already know how to use it now.
Using jQuery validation, you can use this method (http://jqueryvalidation.org/jQuery.validator.addMethod) to add a validator that uses JavScript regex matching to return true or false if the input matches your pattern. This is a very easy way to integrate with the library you're using.
If you want to literally prevent the user from typing characters other than those, you need to attach an event handler to the inputs and block those characters on the keyDown event.
Either way, the matching logic is the same.

Prompt with hints in Javascript

I'd like to get some input from the user:
keywords = prompt("Input keywords separated by commas", "");
I have many various strings stored in an SQLite database that could suggest the user what to type.
Let's say you have an array or list of these strings. How would you code this hinting in Javascript? Are there some functions or code snippets for this functionality?
I'd like it to work similarly as here. When you start typing you get hint with possibilities. There is only one disadvantage, that you can't input more strings separated by commas. Here is this feature working with more strings.
Is prompt() function suitable for this purpose? You can use another way of getting user input.
Thank you
You cannot tweak the native prompt() javascript method.
I know you did not tag with jQuery but would be way easier to use a library to implement such a behavior.
You'll have to build your own dialog system using maybe jQuery UI Dialogs. They have an option to make it modal so the UI is blocked until the dialog is closed.
jQuery UI Dialog will not block javascript execution though like prompt does. You might need to be able to execute code when the dialog is closed. This answer show a way to implement that easily.
Finally, the jQuery UI Autocomplete provides an example on how to use it for multiple values in the same input. They use a comma-separator but I guess you could modify the example to work with whitespaces: jQuery UIAutocomplete Multiple Values
You can't really use any custom functionality with prompt().
You'd be better off creating an <input type="text"/> and hooking the whole thing up to a button, making the data get submitted whenever a use clicks it, or presses enter. Then code it to fetch an autosugges value whenever the user types in a new character.
You should take a look at jQuery UI's autocomplete component (it works with multiple strings as an input as well). You would also need to set up a server-side script that will take a possibly incomplete string as an input and output a possible list of matches back to the browser.

Categories