JQuery Tokenizing Autocomplete w/ trigger key - javascript

Is there a good solution to create textfield inputs like those of Facebook or Google+ status updates and posts where a tokenizing autocomplete is allowed to happen after certain trigger keys like "#" or "+"?
It seems like there are a couple of good tokenizing autocomplete plugins but I'm trying to find a way to call the autocomplete only when the key is present before a term but let's the user type plain non-autocompleted text otherwise.
It seems like you might be able to hack something together with bind but I'm pretty new to JavaScript so if there is a simple more elegant solution I'd love to hear it.

Using jquery is not very difficult. First set a class to identify your input boxes. For example:
<input type="text" class="autocomplete" name="the_name" />
Then, you can simply capture the keyup event and check for the key you need. For example, # symbol has the keycode 64
$(".autocomplete").keypress(function(e) {
if (e.which == 64) {
// your event handler
}
});
You can see all event codes and more info about .keypress() here.
Your event handler may use the jquery.ajax function to ask the server for the data to fill your selector.
If you want to autocomplete after entering some text, for example if the user writes "#tyle" you have to modify the condition in the above code, to get the last word written and check if it has an # at the beginning.

Related

How to restrict from entering a decimal value in input type number?

So I want to have an input of type number <input type="number"> and I want to RESTRICT users from ENTERING DECIMAL VALUE
Note: I'm hiding the spin buttons of the input type text. Know more here
EDIT: ANYTHING WILL WORK! EVEN JAVASCRIPT!
I searched a lot but found nothing.
I did find this answer but it basically blocks the use of any other key on the keypad except the number keys, so the basic problems occur such as the user cannot use backspace and cut the number entered, another problem is the user cannot use tab to change focus onto the next input.
Thank You!
Preventing user input can be done with JavaScript. I'd use the input event for catching values, as it's a unified interface, encompassing any input method you can think of keyup, paste, pointer events, touch events, etc...
document.querySelector('input').addEventListener('input', e => {
e.target.value = Math.round(e.target.value.replace(/\D/g,''))
});
<input>
But you really should not do it! For at least the following reasons:
Forbidding user input is, by and large, perceived as disrespectful and drives users away. In short, it reduces any user engagement metric you can think of (funneling, sales, visits, sharing, etc...). Don't take my word for it. Do some A/B testing: present the same form with and without blocking user input and look at the results.
Form elements are just tools to help users give you data. But they are completely by-pass-able. If you give me a form I can send whatever I want using it, by simply opening the browser console. The validation must be done on server side. If you're using the value to do something on client side, sanitize the input value in the method, without changing user input.
A respectful way to inform users decimal values are not valid is by making the input :invalid, using the pattern attribute ( e.g: pattern="[0-9]"), styling accordingly (e.g: :invalid { border-color: red }), and displaying an appropriate message.
Don't delete or block user input. They'll do it themselves if you tell them why the value is invalid.
When following web standards, your solution lasts. When you come up with hacks, there will always be the odd device in which your hack doesn't work. You don't know where things will be in 1-2 years from now, nevermind 5 or 10.
Last, but not least, have a closer look at Constraint Validation. You'll need to know and use it when creating quality UX and accessible forms.
This is one option for creating an input element using javascript to limit the values that can be entered. I create an array of allowed keys, including all the digits, backspace, and tab as you specified. I added an event listener for the keydown event, and if the key pressed is not in the allowed group, I prevent the default action, or prevent the value from being entered.
I also added an event listener to the paste event, as you could right click paste and enter information that does not meet the criteria. Instead of trying to validate pasted values I disable pasting all together.
If you have any questions, please ask.
const allowedKeys = [..."0123456789", "Backspace", "Tab"];
const myInput = document.querySelector("input");
myInput.addEventListener("keydown", e => {
const key = e.key;
const allowed = allowedKeys.includes(key);
if (!allowed) e.preventDefault();
});
myInput.addEventListener("paste", e => e.preventDefault());
<input type="number">

how to handle an "enter" in a q-input / preventDefault on submit?

I have a text input field, something like:
<q-input
#blur="checkTextAnswer"
#keyup.enter="submit"
#keydown="checkEnterKey"
v-model.trim="textInput"
When the user hits enter I want to treat it like a submit, ie to handle the input and not add an extra newline in the text.
It's a bit like preventDefault from JQuery days. I did find this:
https://quasar-framework.org/components/other-utils.html
but seems for more general DOM events
I also tried just modifying the string (str.replace the newline) but even that hack has an ugly delay.
You need to use the vue event modifier ".prevent" in your event. It also needs to be a #keydown event since the "add newline" event is called with #keydown events in inputs of type "textarea".
The solution would be:
<q-input
type="textarea"
#keydown.enter.prevent="submit"
v-model.trim="textInput"
EDIT:
The 'submit' is a method that you have to define. Here's an example I made in codepen:
Codepen example
If you instead want to submit a form when pressing enter you can just use javascript for this.
this.$refs[refKeyYouGaveToYourForm].submit()

Fill an input field that is not of type text and that triggers events in CasperJS

I have to do automated tests on a website and I want to use CasperJS to learn. For proprietary reasons I can not give too much code.
Here is the example of the input that I am trying to fill:
<input data-bind="value: firstname, valueUpdate: ['blur'], css: {valid:(firstname.isValid() )} " title="" class="valid" aria-required="true" id="firstname" name="firstname">
As you can see, this input is not of type text and has no value attribute. Therefore, I can not use the casper.fill() method. Furthermore, if I enter the web page scope using evaluate() and change the input value using document.querySelector, the change will not be permanent as of the events attached to the text change on the input will not be triggered.
Here is my code:
this.waitForSelector('#memberTitle', function then(){
var testname = 'thisIsNotPermanent';
this.evaluate(function(testname){
document.querySelector('#firstname').value = testname;
}, testname);
});
If I capture the screen right after, I will see my text written in the input box. However, if I wait 500ms and take another capture, the text is gone as, I suppose, the events are triggered or just cleaned because it actually failed to trigger correctly.
The events attached to the input are of Blur, Change and Keypress.
Using CasperJS, how could I go to the lowest level possible to mimic a user using his keyboard and fully use the website's functionalities already in place?
The whole point of those tests are to work with what is in place. The idea is to not have to manually go through the JavaScript of the web site.
That's exactly what the casper.sendKeys(selector, keys) function is for which will send native keypresses and (hopefully) trigger the events on that text element:
this.waitForSelector('#memberTitle', function then(){
var testname = 'thisIsNotPermanent';
this.sendKeys('#firstname', testname);
}).wait(20, function(){
this.capture('screenshot.png');
});
<input> elements without a type attribute default to Text type.
This answer is here to complete the question from another angle. As Artjom B. mentionned, the correct way to fill an input and to trigger its events is by using the sendKeys() function. However, if you ever have a case, like mine, where the events will not trigger or will take a certain amount of time, know that you can trigger those manually.
If you use the firefox inspector tool, you will see that your input or tag will have an event attached to it marked as ev. If you select it, you will have a breakdown of all the events, in order, that are triggered.
You can see that the jQuery click() event will be called. In casperjs, from the evaluate scope you can now do this :
this.evaluate(function(){
$(".discard-answer").click();
})
From there, you can chain jQuery events, like in my case where I had to .blur().change().click();
It is important to know if the event is jQuery or not.
Hope this helps.

Capture key input on select (dropdown list) in JavaScript

I'm trying to capture the input on a dropdown in JavaScript when it is focused, but it appears to not throw events.
Without using a third party library, is there anyway to capture this input?
Example: http://jsfiddle.net/m4tndtu4/11/
you don't want a third party library, but tagged your question to jquery.
you also use jquery code inside your jsfiddle, and mix it with native js...
so i assume, that you would at least want to use jquery.
i edited your fiddle the following: http://jsfiddle.net/m4tndtu4/14/
i just deleted everything you wrote, and just entered one 'on' handler:
$("#sel1").on("keyup",function(){ //this captures selection changes
$("#output").css("background-color", "yellow").text($('#sel1 option:selected').text()); // change the css of output and set the text to the value of the selected option
var enteredSearchSequence = String.fromCharCode(e.which);
$("#input").css("background-color", "yellow").text(enteredSearchSequence);
});
currently, it shows only the last pressed key - and also don't work if SHIFT was pressed... but i guess, you can figure out, how to concat the keypress or even delete it, because it's treated as a new search.
btw. given that, you may want to take a look at angularjs or any other mvc - a list and a searchbox is quite easy with those frameworks!

Validate and format the value of an input

I have a input text box to take in an amount of money. I would like two things.
First, validate to not allow things like this
1,23.00
1,123.45.67
But these would be OK:
123456.00
123,456.00
123,456
Secondly, if 123456 is entered, I would like it to change to 123,456.00 once the user clicks out of the box.
The second part is what I'm unsure about, if there is something that did both though, that would be great.
1) Google for some nice plugin, you will find many validation scripts on the web.
2) You can use the blur or change event for that. Add an event listener for them, which sets the appropriate format to the input value.

Categories