How to detect if user has left the input field? - javascript

Suppose I have an input field,
<input id="city" placeholder="city">
and I want to detect whenever user leaves this field. How can I do so?

Normal javascript
var element = document.getElementById("ELEMENT_ID");
element.addEventListener("blur", function() { ... your code here ...});
jQuery
$("#ELEMENT_ID").on("blur", function() { ... your code here ...});
If, by any chance, you're implementing those self-emptying fields with predefined text, use placeholder attribute. If you're changing style based on focus, use :focus CSS selector. Also, change event is emitted if user leaves the field and changed it's contents.

When an element loses focus, the onblur event is fired.
var elem = document.getElementById('city');
elem.addEventListener("blur", function( event ) {
console.log('Elvis has left the city (input)!');
}, true);
https://developer.mozilla.org/en-US/docs/Web/Events/blur

Related

How to mirror an input field to another input field?

I have an input field and multiple input fields, the original input field is the primary field that gets submitted.
So, I need to mirror one field to the main field.
I tried watching the keyup and change events but when the user pastes with the mouse it does not work, because the event is triggered before the user presses paste and not after it.
I am not sure that this is the best way to mirror two fields, so I am asking you if you have better methods of doing it
Is there an event that can be triggered after the paste is pressed?
Instead of triggering on key/mousevents, you could try using an "input" event on the input element you would like to mirror.
const ogInput = document.getElementById("og")
const mirrorInput = document.getElementById("mirror")
ogInput.addEventListener("input", () => {
mirrorInput.value = ogInput.value
})
<input type="text" id="og" />
<input type="text" id="mirror" />

Simulating Enter Key Press on Input in Karma/Jasmine Tests

I am trying to test user search functionality inside an angular custom component. The input (and only input) in the directive template that I am trying add text to and trigger the search is:
<input type="text" ng-model="searchInput" class="form-control search"/>
I would like to add a text value of "User" into that input above. Test to make sure it has that value, and then simulate an enter key press to then select the first matching node.
Get the input element
Add text to the input
Test to make sure the input value is correct
Press enter on the input
Text to make sure the first matching item in the search is correct
Have tried:
it ("should search for the specified node", function () {
var value = "User is not registered"
var input = diagramDirective.find("input");
$(input).val(value).trigger("input");
scope.$apply();
//why can't I trigger a click event here by doing something like
var e = jQuery.Event("keypress");
e.keyCode = 13;
$(input).trigger(e);
}
Thanks
You need to match your JQuery.Event to whatever is triggering the final search in your controller, so if your controller is listening for a keypress, then you need to make sure your jQuery.Event is a "keypress" event, but if your controller is listening for a "keyup" you need to set your jQuery event to "keyup". You also need to look for the matching item in the callback of the actual event
it("should search for the specified nodes", function () {
var value = "User is not registered";
var e = jQuery.Event("keypress");
e.keyCode = 13;
// find the input
var directiveElementInput = diagramDirective.find("input");
// Set some text!
$(directiveElementInput).val(value).trigger("input");
// make sure the input has the value
expect(directiveElementInput).toHaveValue(value);
// execute the event on the input and check for the selected item
$(directiveElementInput).keypress(function () {
// do your check here for the matching item here
}).trigger(e);
});
I would recommend taking a look at the event listeners on the input box, because an input box isn't necessarily always triggered by the "enter" keypress. Some other possible events that it may be listening to are, "blur", "keyup", "change". Depending on if its an event listener or an on-whatever event, you'll have to trigger it accordingly.
Sorry this is kind of vague, but it's hard to say without knowing the event listeners attached to the input box.
Hope this helped!

Populate hidden field with autocomplete value

I have an HTML form with a regular text input and a hidden field.
I also have the following code that will populate the hidden field with the value of the text field either when it is changed, or if the text field has a default value (supplied by the page itself):
$(document).ready(function() {
var emailinput = document.getElementById('emailval');
document.getElementById('usernameval').value = emailinput.value;
emailinput.onkeyup = function() {
document.getElementById('usernameval').value = emailinput.value;
}
emailinput.onblur = function() {
document.getElementById('usernameval').value = emailinput.value;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="email" id="emailval" />
<input type="hidden" name="username" id="usernameval" />
This works well, except in the case where the browser autofills the text field. If the user submits the form without changing the textfield.
So my question is, is there any way to have the javascript pull the value from the browser-autofilled text field?
Attach an event handler on the form's submit event, and copy the value of #emailval to #usernameval. For example, let's say your form has the ID, #form:
$('#form').submit(function (event) {
'use strict';
$('#usernameval').val($('#emailval').val());
});
Documentation: https://api.jquery.com/submit/
What is 'input7'? I'm assuming this is a key. You could add another event for when the mouse leaves the input box, to get that value, since the user has to use the mouse to select the value.
Another thing you might want to consider, is turn off autocomplete on that field.
https://developer.mozilla.org/en-US/docs/Web/Security/Securing_your_site/Turning_off_form_autocompletion
You could use the form's onsubmit event. Here's the pseudo code:-
form.onsubmit= function(e){
e.preventDefault();
document.getElementById('usernameval').value = document.getElementById('emailval').value;
this.submit();
}

html catch event when user is typing into a text input

Im just wondering how I go about catching the event when the user is typing into a text input field on my web application.
Scenario is, I have a contacts listing grid. At the top of the form the user can type the name of the contact they are trying to find. Once there is more than 1 character in the text input I want to start searching for contacts in the system which contain those characters entered by the user. As they keep typing the data changes.
All it is really is a simple type ahead type functionality (or autocomplete) but I want to fire off data in a different control.
I can get the text out of the input once the input has lost focus fine, but this doesnt fit the situation.
Any ideas?
Thanks
Use the keyup event to capture the value as the user types, and do whatever it is you do to search for that value :
$('input').on('keyup', function() {
if (this.value.length > 1) {
// do search for this.value here
}
});
Another option would be the input event, that catches any input, from keys, pasting etc.
Why not use the HTML oninput event?
<input type="text" oninput="searchContacts()">
I would use the 'input' and 'propertychange' events. They fire on cut and paste via the mouse as well.
Also, consider debouncing your event handler so that fast typists are not penalized by many DOM refreshes.
see my try:
you should put .combo after every .input classes.
.input is a textbox and .combo is a div
$(".input").keyup(function(){
var val = this.value;
if (val.length > 1) {
//you search method...
}
if (data) $(this).next(".combo").html(data).fadeIn(); else $(this).next(".combo").hide().html("");
});
$(".input").blur(function(){
$(this).next(".combo").hide();
});

How do you have grayed out text in a textfield that dissapears when the user clicks on it

In HTML & JS, how do you make a textfield that has grayed out text telling the user what the field is for that goes away when the user clicks on the field?
For example, in firefox the search field in the top right hand side says which search engine it uses when there's nothing entered, then once you click it's an empty textfield, but if you leave it blank and remove focus from the textfield then the grayed out text is back again.
Is there a name for this behavior? Also, is it possible to do in pure css without the use of js to do the on focus / on blur events?
The effect that you are referring to is often called the placeholder effect. Within HTML5 this effect is possible within certain browsers by simply placing the new attribute 'placeholder' within your input tag. Such as...
<input type='text' placeholder='Place Holder Text'/>
<input type='text'/> <!-- Example with no title-->
<input type='text' title='Your title'/>
This can also be done in JavaScript using CSS by setting a style for an active class and toggling the active style along with the item's title tag. Such as ...
$(document).ready(function(){
// Select all input fields. (You will probably want to filter this down even further).
var inputs = $('input[type=text]');
// Set all the inputs to the title value.
inputs.each(function(){
$(this).val($(this).attr('title')).addClass('unfocused'); // Styling Class for inputs.
});
// When the user focuses on an input
inputs.focus(function(){
var input = $(this);
if(input.val() == input.attr('title')){
$(this).removeClass('unfocused').val('');
}
});
// When the user loses focus on an input
inputs.blur(function(){
var input = $(this);
if(input.val() == ''){ // User has not placed text
input.val(input.attr('title')).addClass('unfocused');
}
});
});
The tested function can be seen here: http://www.jsfiddle.net/F8ZCW/5/
This behavior is on my URL shortener site: http://relk.in
The basic idea is when the onfocus event fires, you modify the CSS of the textfield to a normal class, and then onblur, you re-apply the previous class.
And no, you cannot do this in pure CSS.
Example:
var textfield = document.getElementById('someTextField');
textfield.onfocus = function() {
this.className = this.className.replace('oldClassName', 'newClassName');
};
textfield.onblur = function() {
this.className = this.className.replace('newClassName', 'oldClassName');
}

Categories