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

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()

Related

Input type=email's change event is not firing when the value entered is whitespace

I've added an on 'change' event listener to a type=email input element. When I add a couple space characters into the email field, then lose focus on that element, the change event doesn't seem to be firing.
However, this exact scenario works just fine with type=text input elements.
What's going on?
$('input[type="email"]').change(e => {
console.log('Triggered!');
});
Browser: Chrome Version 63.0.3239.132 (Official Build) (64-bit)
I originally said that it looks like there is an automatic trim operation performed on email fields because the length of the value is coming back at 0 after typing some spaces and leaving the field, but upon returning to the field, the spaces remain in the element, so they aren't getting trimmed out.
I suspect that, because spaces are not valid for this input type, they are not considered part of the value, thus the value doesn't change when you enter them and the change event doesn't fire.
Type some spaces in the field and then hit TAB to leave the field, but then return to the field. The spaces will still be there.
$('input[type="email"]').on("blur", function(e){
console.log(this.value.length);
});
$('input[type="email"]').on("change", function(e){
console.log("Change fired!");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="email">
You can use something like that:
$('input[type="email"]').on('focusout', {
console.log('Triggered!');
var $trig = $(this);
$trig.attr('trimmed', $trig.val().toString().trim());
$trig.val( '').val($trig.attr('trimmed'));
});
But, as answered above, input[type="email"] does not count whitespaces. It is only works as fast hack;
I am facing the same problem with React, and I don't want to reflect the error on the onBlur event (as other solutions here). I don't think an error should be reflected in any input by the simple fact of removing the mouse from that input. For me that's not User friendly,... AT ALL.
Why?
Because the User might have decided to remove the mouse from that
Input only because he/she simply wants to copy something from somewhere else first,... and then past it there (and/or to past it somewhere else). So technically there is no mistake there yet.
Because I simply want to fill another input field of the form first.
Why? Becase that's precisely the field's value I already copied from
somewhere else, so that's the value I have stored in clipboard, and
it doesn't goes where my mouse landed by default. Or simply because
I just want to! I'm the User, so I can choose the order to
fill the form!
For me is more than enough with validating what the User has written and/or removed/deleted from the Inputs (onChange validation) AND also what the User finally decides to send (onSubmit validation). A proper combination of onChange and onSubmit validation is the perfect healthy balance between thoroughness and User friendly.
A Solomonic "solution":
I am using a custom validation hook. As I can not change the behavior of the input with a type email regarding the white spaces in an OnChange event,... then I decided to use a workaround, which is simply avoiding the typing of white spaces and that's it, as the onChange event won't trigger anyway.
const preventWhiteSpaceOnKeyDown = (e) => {
if (e.key === " ") {
e.preventDefault();
}
}
.
.
.
<input
type={"email"}
id='commentEmail'
name='commentEmail'
required={true}
autoFocus={true}
ref={emailInputRef}
value={emailState}
onChange={emailInputChangeHandler}
onKeyDown={preventWhiteSpaceOnKeyDown}
/>
This is not a "solution". There is no clean solution for this. But after this at least my input[type=email] element won't hold useless white spaces.
input[type="email"] does not fire change event, use blur event instead:
$('input[type="email"]').blur(function(){
console.log('blur event is fired.');
});

jQuery validate not binding to keyup events [duplicate]

This question already has answers here:
onkeyup and onfocusout is not working in jQuery Validate
(1 answer)
jQuery validate plugin: validate on blur() by default
(1 answer)
Closed 5 years ago.
I'm making a "contact me" page, with jQuery validation. My main content box is reloaded with ajax to change content when the user clicks on a new page. The problem I'm having now is to bind an event handler for the validate function. what I got now is
$(document).ready(function(){
$('body').bind('focus focusout keyup', function() {
$('#contact_me').validate({
But it's not working like intended. I have to start typing, then click out of the input field and then click on it again before it starts to validate the input field value. I want it to validate on focus, focusout and keyup. I think the problem is with the event handler somehow. Any suggestions?
Here is a JSfiddle with the script: https://jsfiddle.net/z6h9d028/4/
I can see now that the eventhandler is not the problem. When i type in a input field its not validating the value until i click out of the box. After the first validation i works on keyup as well. How can i get i to work on keyup stright away?
Edit 2:
Updated fiddle: https://jsfiddle.net/z6h9d028/7/
It's almost working now! I just need to get all the error messages to show when clicking the submit button. And to find a way to show the error message when you type one character and then remove it if the input field is required (it does show it if you type once, then remove, type again and remove. but not the first time)
You don't need to set your own event listeners, or at least if you do, you shouldn't be using them on the .validate() method (see alternative method below).
Remove the whole $('body').bind() part, and add the following to your validate settings object:
onkeyup: function(element) {
$(element).valid();
// As sparky mentions, this could cause infinite loops, should be this:
// this.element(element);
},
This should be better too, as it may give you some extra freedom as to how you handle the onkeyup events, such as adding a setTimeout if you don't want it to be instantaneous.
Fiddle: https://jsfiddle.net/z6h9d028/5/
Inside the onkeyup, you can also call $('#contact_me').valid(), which will revalidate the whole form, although that may not be your desired outcome.
Edit: Sparky also helpfully mentioned that jquery-validate by default does allow keyup events, but it only does so after the first submit: jQuery validate plugin: validate on blur() by default
An alternative way would be to set the details of your validation as you currently are, without the onkeyup function, then set your own listeners and run $(element).valid():
$('#contact_me').validate({
rules: {
// ...
}
});
$('input').on('focus focusout keyup', function () {
$(this).valid();
});
Edit regarding your other issues:
Your errorPlacement function is doing some funky things. How it decides what is the next sibling or not seems to be working incorrectly. Also, you're adding the error HTML divs into your DOM manually, but they are actually generated by the plugin. So really, you're creating both, then trying to show them, kinda over-riding the plugin, kinda not, and the whole thing is going into a frenzy.
The solution is, I reckon, to remove those error divs, remove that errorPlacement function, and then modify the CSS selectors to get any id ending with "-error", which is what the plugin generates. So [id$='-error'] instead of .error_message
https://jsfiddle.net/z6h9d028/8/

JQuery Tokenizing Autocomplete w/ trigger key

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.

How can I get the new value of a HTML text element in a key event handler, also for special keys?

Lets suppose we have a html text input element and it has text "abc" and cursor is between "b" and "c". If we press backspace key then how can we get the value "ac"?
Please note that in case of special keys KeyPress event do not fire. The only events that fire are KeyDown and KeyUp and none of them has the value after the effect of special key is applied. The effect is visible after the eventhandlers of these events exit but since we have only these two events we have to somehow get the affected/latest value inside these events.
We can go to a complex way by manually applying the effect ourselves but its very very complicated given the facts that we have to find the cursor position, write different code for different special keys and bring browser compatibility. The browser, whichever it is, is already applying the effect once the eventhandlers exit but is there some way to get that latest value in those events without manually applying it or in some other event?
Please note that I am not searching for "how to find which key is pressed". I can find that by looking at the event object inside the KeyDown or KeyUp event handlers. I want to apply the effect of the special key without using a lot of manual code.
I have already looked at Capturing HTML Text Input Key press after key has been applied?. Its talking about a different thing than my question.
My ultimate task is to have a web page with only two controls: a textbox and a button. The button is initially disabled. User can type in textbox and on every key its checked that there is some text in the textbox, if there is then button is enabled, if not then button is disabled. The difficult part is to take into consideration special keys such as delete, enter, tab, backspace.
Note: I do not want to work on the blur eventhandler of the HTML text element because it affects the tab order.
Example using jQuery. The target value is stored on the title attribute, but you could make this an ajax request, or whatever logic you need. In the following case, typing 'abc' in the text box will make the go button enabled.
HTML:
<input type="text" title="abc" id="in">
<input type="button" id="go" value="Go" disabled="disabled">
Javascript:
$("#in").keyup(function() {
if($(this).val() == $(this).attr("title")) {
$("#go").removeAttr("disabled");
}
});
JSFiddle

Selectively enable enter key in HTML textarea (javascript)

I am using openjs.com's shortcut handling (1)
to disable the enter key in my html forms. However, inside of textareas in those forms I want enter key to emit the normal CR-LF pair (because that's what users expect).
At the moment assuming I have a form/input structure as follows:
<form id="f1">
<fieldset>
<input>
<textarea id="f2"> ...
The following scripts are run:
shortcut.add('Return', function () { /*empty*/ },
{ 'type':'keydown', 'disable_in_input':false,'propagate':true,
'target':document.getElementById('f1')});"
This effectively disables the enter key.
I have tried using the following code to re-enable it for the textarea:
shortcut.add(\"Enter\", function() { }, {'type':'keydown','propagate':false,
'disable_in_input':false, 'target':document.getElementById('f2') } );
But that does not work. What is the order of propagation of this event? Should it bubble up from the textarea or bubble down from the form element?
It doesn't look like this library was really meant to be used this way. I would hazard a guess that adding any shortcut disables the browser's handling of it entirely, no matter what you do afterwards.
What are you actually trying to accomplish? If you just want to prevent the form from being submitted, you could add a submit event listener for the whole form that calls event.preventDefault().

Categories