I have this code, basically I have <input id="register_username" type="text" name="username"> and I want to check if the users already exist in the database or not. The code works perfectly when the user type a username, but sometimes some browsers (for example Firefox) gives the user drop down menu and let them choose some values they already entered in the past (such as their name). The problem is when the chose the username from the drop down menu, the keyup function does not work. How can I fix this problem ?
$("#register_username").live('keyup', function() {
$.post('scripts/register/register_check.php', {
checkusername: $('#register_username').val()
}, function(data) {
if (data == "good") {
//do something
} else {
//do the other thing
}
});
});
I don't think all browers if any triggers an event after choosing an option from an autocomplete dropdown.
Your best bet is to use .change() which will trigger after the element loses focus. For example, when the user chooses an autocomplete option and move on to the next field.
I would use the onblur event to fire whenever the field loses focus.
Related
I've come across some kind of bug I believe with angular and chrome and I am not quite sure what the solution is, my angular application has custom input controls and these inputs do some stuff on focus (focus)="someEvent($event). These inputs are the username and password field so chrome stores the values. Upon loading the page again, chrome will apply the stored values, if a user clicks elsewhere on the screen (NOT on the input components), both of the input components fire the focus event.
I could understand if this happened on page load as chrome may cycle through the inputs and apply the stored values, however this happens after the first mouse click anywhere on the page.
Is there a way to interpret that these focus events were cause by the autofill feature and not the user focusing on the input manually?
I have some code on these events that do event.target.select() to select all text, and oddly enough.. the 2 inputs end up getting stuck in a focus loop. The first gets focused then the second then the first then the second forever until a user presses tab.
HTML:
<input [ngClass]="inputClass" [type]="this.type" [readOnly]="this.readonly || (this.ParentPanel && this.ParentPanel.readonly)" [ngStyle]="inputStyle" [disabled]="disabled || (this.ParentPanel && this.ParentPanel.disabled)" [(ngModel)]="value" (change)="Event_change($event)" (keyup)="Event_keyup($event)" (keydown)="Event_keydown($event)" (focus)="Event_focus($event)" maxlength="512"/>
TS:
Event_focus(event) {
console.log('focus event' , event);
if (this.selectAllOnFocus) {
setTimeout(() => { // required to work with Edge (OnFocus happens before some browser properties are set)
event.target.select();
});
}
this.OnFocus.emit(event);
}
Thanks.
I figured this out, Before the code gets called - I have it check whether or not the control is the documents activeElement.
if (this.selectAllOnFocus && this.element && this.element.nativeElement === document.activeElement) { //do rest here }
These appears to work and resolve my issue.
Is it possible to validate the text fields while user is entering the data?
For instance, If the user selects one checkbox in the form, does not enter data in the text field, and moves on to the next checkbox, the form should generate an error immediately, prompting the user to enter data for the previously selected checkbox. In other words, user will not be able to proceed unless each section
is done correctly (vs. error messages at the end of the form when the submit button is clicked)
Thank You!
There are plenty of plugins that will do this for you.
jQuery form validation plugin: This one is good
If you are determined to do it manually then you would want to use something like:
$('input').on('change', function(){...});
Here are some examples for javascript blur/focus:
https://javascript.info/focus-blur
For something you can play with, here's a jsfiddle I threw together. It uses jQuery's on focus and blur events. It checks if any of the previously "required" fields were left blank (or unchecked).
$(document).ready(function() {
function checkCheckbox(jEl) {
return jEl.is("input[type='checkbox']:checked");
}
function checkTextbox(jEl) {
return jEl.is("input[type='text']") && jEl.val() != ""
}
function validate(el) {
el.parent('div')
.prevAll('div:has(".required")')
.add(el.parent('div'))
.addClass('error')
.each((i, e) => {
jEl = $(e).children('.required');
if (checkCheckbox(jEl) || checkTextbox(jEl)) {
$(e).removeClass('error');
}
})
}
$(".required").on("focus blur", function() {
validate($(this))
});
});
i have a function that currently working on .keypress event when the user right something in the textbox it do some code, but i want the same event to be triggered also when the user clear the textbox .change doesn't help since it fires after the user change the focus to something else
Thanks
The keyup event will detect if the user has cleared the box as well (i.e. backspace raises the event but backspace does not raise the keypress event in IE)
$("#inputname").keyup(function() {
if (!this.value) {
alert('The box is empty');
}
});
jsFiddle
As Josh says, this gets fired for every character code that is pressed in the input. This is mostly just showing that you need to use the keyup event to trigger backspace, rather than the keypress event you are currently using.
The solution by Jonathon Bolster does not cover all cases. I adapted it to also cover modifications by cutting and pasting:
$("#inputname").on('change keyup copy paste cut', function() {
//!this.value ...
});
see http://jsfiddle.net/gonfidentschal/XxLq2/
Unfortunately it's not possible to catch the cases where the field's value is set using javascript. If you set the value yourself it's not an issue because you know when you do it... but when you're using a library such as AngularJS that updates the view when the state changes then it can be a bit more work. Or you have to use a timer to check the value.
Also see the answer for Detecting input change in jQuery? which suggests the 'input' event understood by modern browsers. So just:
$("#inputname").on('input', function() {
//!this.value ...
});
Another way that does this in a concise manner is listening for "input" event on textarea/input-type:text fields
/**
* Listens on textarea input.
* Considers: undo, cut, paste, backspc, keyboard input, etc
*/
$("#myContainer").on("input", "textarea", function() {
if (!this.value) {
}
});
You can check the value of the input field inside the on input' function() and combine it with an if/else statement and it will work very well as in the code below :
$( "#myinputid" ).on('input', function() {
if($(this).val() != "") {
//Do action here like in this example am hiding the previous table row
$(this).closest("tr").prev("tr").hide(); //hides previous row
}else{
$(this).closest("tr").prev("tr").show(); //shows previous row
}
});
Inside your .keypress or .keyup function, check to see if the value of the input is empty. For example:
$("#some-input").keyup(function(){
if($(this).val() == "") {
// input is cleared
}
});
<input type="text" id="some-input" />
I have a form that detects if all the text-fields are valid on each keyup() and focus(); if they're all valid, it will enable the submit button for the user to press. However, if the user fills in one of the text inputs with a browsers autocomplete feature, it prevents the submit button from being enabled.
Is there a way to detect if any of the input has changed regardless of how it's been changed, using jQuery?
You could try using on input to detect text-based changes (except keys like ctrl and shift) in <input>'s.
For example:
$(input).on('input', function() {
console.log($(this).val());
});
The jQuery change event will only fire on blur. The keyup event will fire as you type. Neither fire on clicking an auto-completion option. I am also searching for a way to detect this, but I'm currently going with
$(selector).bind("change keyup",function(){
//Do something, probably with $(this).val()
});
But it doesn't quite solve the problem...
Myself I used
$(selector).on("change keyup blur input", function() {});
which did the trick in Chrome. input is what made it work for autocomplete.
My issue was detecting auto-fill (via a plugin like lastpass or 1password) as well as the issue described above.
The solution that worked for me was:
$(function(){
function validate(){
if($('#email').val() !== '' && $('#password').val() !== '')
$('#submit').prop('disabled', false);
else
$('#submit').prop('disabled', true);
}
// Validate after user input
$('#email, #password').on('keyup change', validate);
// Validate on mouse enter of body and login form
// to catch auto-fills from roboform/1password etc...
$('body, #loginform').on('mouseenter', validate);
// Validate onload incase of autocomplete/autofill
validate();
});
See demo in JSFiddle.
You could use the jQuery .change() function.
After the page initially loads, you can validate the entire form, just to check that it is in fact not filled in. After that you can use .change() to check if things have changed on the form, and if anything has changed, validate the form again.
$(document).ready(function() {
// validate form once, just to be sure (if valid, activate submit button)
});
...
<form>
<input class="target" type="text" value="Field 1" />
<select class="target">
<option value="option1" selected="selected">Option 1</option>
<option value="option2">Option 2</option>
</select>
</form>
<script type="text/javascript">
$('.target').change(function() {
alert('Something changed');
// Try validating form again (if valid, activate submit button)
});
</script>
Plan B
Another option is to always have the submit button clickable, but use .submit() to bind it to the form validator. Then if the form IS valid, carry on. If the form IS NOT valid use .preventDefault() to stop the submission of the form..... and you'd display a warning message too, indicating the missing fields.
The answer has been given in this question. It doesn't use jQuery, but it works for Autocomplete:
Use js onpropertychange event.
I have a decent solution after having the same problem. Set keyup as normal to our form fields, then mouseover to the surrounding div. So once you click the autocomplete option, you mouse will be over the top of the div:
$("#emailaddress").bind("keyup", function() {
displayFullSubcribeForm();
});
$(".center_left_box").bind("mouseover", function() {
displayFullSubcribeForm();
});
I wanted a very good user experience on a field where it would not be invalid (turn red in my case) as long as the user was reasonably active e.g. still filling out the field.
To do this for normal input, I was able to hook up to keyup with a debounce function, while blur is connected for immediate validation. While it appears that keyup is triggered by lastpass, since I have debounced it, there was a delay in validation. Thanks to #peter-ajtai I tried to add the change event and it indeed catches last pass and leaves the other niceties alone.
Coffeescript example:
#fieldExp
.keyup($.debounce(#_onExpChange, 3000))
.blur(#_onExpChange)
.change(#_onExpChange)
This worked well and lastpass form fill triggers immediate validation.
this is the ultimate solution, guaranteed to work
$(document).bind('mouseover', function(){
liveValidate();
});
I have some text inputs which I'm validating when a user tabs to the next one. I would like the focus to stay on a problematic input after showing an alert. I can't seem to nail down the correct syntax to have JQuery do this. Instead the following code shows the alert then focuses on the next text input. How can I prevent tabbing to the next element after showing an alert?
$('input.IosOverrideTextBox').bind({
blur: function(e) {
var val = $(this).val();
if (val.length == 0) return;
var pval = parseTicks(val);
if (isNaN(pval) || pval == 0.0) {
alert("Invalid override: " + val);
return false;
}
},
focus: function() {
$(this).select();
}
});
I don't like forced focus, but can't you just focus after the blur takes place?
element.focus();
If doing that in the blur event doesn't always work (I'm not sure exactly when it fires, before or after the actual blur takes place), a redundant timeout will do, as well: setTimeout(function () { element.focus() }, 0).
But please don't do this. Heck, you should never be using alert or any kind of modal dialog for a web interface, either. How about adding a invalid class to the form field, putting a message off to the side of it, and disabling submit until all fields are valid? That's a much less invasive solution that allows me to fill out the form in whatever way is best for me, rather than whatever way is simplest for you.
You can do this with the validation plugin by default.
focusInvalid default: true
Focus the last active or first invalid element on submit via validator.focusInvalid(). The last active element is the one that had focus when the form was submitted, avoiding to steal its focus. If there was no element focused, the first one in the form gets it, unless this option is turned off.
Then you'd only need to have the focus event handler do your select and let the plugin handle validation.