I use the native HTML date pickers. I want to achieve that the parent form is submitted when a date is selected by the datepickers browsers provide.
If the date is input by keyboard, I only want to submit if the enter key is pressed or on focusout.
Now my problem is that I cannot distinguish between date picker input and keyboard input, at least in Firefox. Some examples:
$(this).on('input', function(event) {
console.log(event.type);
}
This always logs 'input', no matter what I do - I would have expected that to be either "click" or "keydown" or something alike.
The on('click') handler only fires when I click on the input field, not when I click something in the date picker...
Can someone push me in the right direction?
Thanks alot
Philipp
I did a workaround which is close to what I want:
$('#eooMainForm input[type="date"]')
.each(function() {
$(this).data('serialized', $(this).serialize());
$(this).on('focusout', function() {
if($(this).serialize() != $(this).data('serialized')) {
$("#eooMainForm").form('submit');
}
});
$(this).on('keypress', function(event) {
$(this).data('byKeyPress', 1);
});
$(this).on('click', function(event) {
$(this).data('byKeyPress', 0);
});
$(this).on('change', function(event) {
//if change was done by date picker click
if($(this).data('byKeyPress') != 1 && $(this).serialize() != $(this).data('serialized')) {
$("#eooMainForm").form('submit');
}
});
});
So a keypress event listener sets the "flag" "byKeyPress" to 1, while a click events listener sets it to zero. This way, I can determine in the change event listener what caused the change.
The only situation where this does not work is when a user starts typing the date but then selects it by clicking the datepicker. I can live with that.
You'll need to attach an event which supports both event types. Using JQuery: $('a.save').bind('mousedown keypress', submitData(event, this));
Then create a JS condition:
function submitData(event, id)
{
if(event.type == 'mousedown')
{
// do something
return;
}
if(event.type == 'keypress')
{
// do something else
return;
}
}
You can find all the list of event in this image.
$('input').on('blur', function(event) {
alert(event.type);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" />
You can apply all event like the above example. Above example applied blur event on input.
Is there any way I can create a constant function that listens to an input, so when that input value changes, something is triggered immediately?
I am looking for something using pure javascript, no plugins, no frameworks and I can't edit the HTML.
Something, for example:
When I change the value in the input MyObject, this function runs.
Any help?
This is what events are for.
HTMLInputElementObject.addEventListener('input', function (evt) {
something(this.value);
});
As a basic example...
HTML:
<input type="text" name="Thing" value="" />
Script:
/* event listener */
document.getElementsByName("Thing")[0].addEventListener('change', doThing);
/* function */
function doThing(){
alert('Horray! Someone wrote "' + this.value + '"!');
}
Here's a fiddle: http://jsfiddle.net/Niffler/514gg4tk/
Actually, the ticked answer is exactly right, but the answer can be in ES6 shape:
HTMLInputElementObject.oninput = () => {
console.log('run'); // Do something
}
Or can be written like below:
HTMLInputElementObject.addEventListener('input', (evt) => {
console.log('run'); // Do something
});
Default usage
el.addEventListener('input', function () {
fn();
});
But, if you want to fire event when you change inputs value manualy via JS you should use custom event(any name, like 'myEvent' \ 'ev' etc.) IF you need to listen forms 'change' or 'input' event and you change inputs value via JS - you can name your custom event 'change' \ 'input' and it will work too.
var event = new Event('input');
el.addEventListener('input', function () {
fn();
});
form.addEventListener('input', function () {
anotherFn();
});
el.value = 'something';
el.dispatchEvent(event);
https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Creating_and_triggering_events
Another approach in 2021 could be using document.querySelector():
const myInput = document.querySelector('input[name="exampleInput"]');
myInput.addEventListener("change", (e) => {
// here we do something
});
This sounds exactly like the problem I had.
And I would have stated the same question, but I guess it's the same wrong question...
IMHO it's just 'onchange' mistaken as 'oninput' which are 2 different things.
Give me a lot of minus for this statement, I dont care, but I guess it may help one or the other ...
HTML form input contain many events. Refer from MDN document, on the sidebar go to Events menu and expand it. You will see many useful events such as beforeinput, change, copy, cut, input, paste, and drag drop events.
iput & change.
The beforeinput, and input events are fired by order when you type the form input value.
When the form input value has changed and you lost focus on that input, the change event is fired.
Cut, copy, paste.
When you cut (CTRL+X on keyboard shortcut) the input value, the cut, beforeinput, input events are fired.
When you copy (CTRL+C on keyboard shortcut), the copy event is fired alone.
When you paste the value from clipboard (CTRL+V on keyboard shortcut), the paste, beforeinput, input events are fired.
JS change value.
To change input value by JavaScript and make important events work, you need to dispatch at least 2 events by order. One is input and two is change. So that you can focus your code to listened to input or change event. It's easier this way.
Here is all sample code.
(() => {
let inputText = document.getElementById('text');
let submitBtn = document.getElementById('submit');
let triggerJSBtn = document.getElementById('button');
submitBtn.addEventListener('click', (event) => {
event.preventDefault(); // just prevent form submitted.
});
triggerJSBtn.addEventListener('click', (event) => {
const thisTarget = event.target;
event.preventDefault();
inputText.value = thisTarget.innerText;
inputText.dispatchEvent(new Event('input'));
inputText.dispatchEvent(new Event('change'));
});
inputText.addEventListener('beforeinput', (event) => {
const thisTarget = event.target;
console.log('beforeinput event. (%s)', thisTarget.value);
});
inputText.addEventListener('input', (event) => {
const thisTarget = event.target;
console.log('input event. (%s)', thisTarget.value);
});
inputText.addEventListener('change', (event) => {
const thisTarget = event.target;
console.log('change event. (%s)', thisTarget.value);
});
inputText.addEventListener('cut', (event) => {
const thisTarget = event.target;
console.log('cut event. (%s)', thisTarget.value);
});
inputText.addEventListener('copy', (event) => {
const thisTarget = event.target;
console.log('copy event. (%s)', thisTarget.value);
});
inputText.addEventListener('paste', (event) => {
const thisTarget = event.target;
console.log('paste event. (%s)', thisTarget.value);
});
})();
/* for beautification only */
code {
color: rgb(200, 140, 50);
}
small {
color: rgb(150, 150, 150);
}
<form id="form">
<p>
Text: <input id="text" type="text" name="text">
</p>
<p>
Text 2: <input id="text2" type="text" name="text2"><br>
<small>(For lost focus after modified first input text so the <code>change</code> event will be triggered.)</small>
</p>
<p>
<button id="submit" type="submit">
Submit
</button>
<button id="button" type="button">
Trigger JS to set input value.
</button>
</p>
<p>Press F12 to view results in your browser console.</p>
</form>
Please press F12 to open browser's console and see result there.
Each time a user inputs some value, do something.
var element = document.getElementById('input');
element.addEventListener('input', function() {
// Do something
});
Keydown, keyup, input are events that fire immediately when input changes,
I would use keydown or input events to get the changed value from the input box.
const myObject = document.getElementById('Your_element_id');
myObject.addEventListener('keydown', function (evt) {
// your code goes here
console.log(myObject.value);
});
If you would like to monitor the changes each time there is a keystroke on the keyboard.
const textarea = document.querySelector(`#string`)
textarea.addEventListener("keydown", (e) =>{
console.log('test')
})
instead of id use title to identify your element and write the code as below.
$(document).ready(()=>{
$("input[title='MyObject']").change(()=>{
console.log("Field has been changed...")
})
});
i am trying to create jQuery plugin which needs to trigger on keyup of input tag.
But, somehow its not working :(
I've tried it so far:
JS:
$.fn.search_panel = function() {
if($(this).prop("tagName").toLowerCase() == 'input'){
var input_str = $.trim($(this).val());
console.log($(this));
onkeyup = function(){
console.log(input_str);
}
}
};
Plugin Initialization
$(document).ready(function(){
$('input').search_panel();
});
HTML:
<input type="text" />
From the above code, it only console when page loads for the first time, but after entering anything in input box it doesn't console.
You're inadvertantly binding to the window's onkeyup event. You should use $(this).on instead to bind to the individual keyup event on each input:
$.fn.search_panel = function() {
// Iterate all elements the selector applies to
this.each(function() {
var $input = $(this);
// Can probably make this more obvious by using "is"
if($input.is("input")){
// Now bind to the keyup event of this individual input
$input.on("keyup", function(){
// Make sure to read the value in here, so you get the
// updated value each time
var input_str = $.trim($input.val());
console.log(input_str);
});
}
});
};
$('input').search_panel();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input><input><input><input>
Add keyup event inside plugin and bind it to current input,
$.fn.search_panel = function () {
if ($(this).prop("tagName").toLowerCase() == 'input') {
$(this).keyup(function () {
var input_str = $.trim($(this).val());
console.log($(this));
console.log(input_str);
});
}
};
Demo
focusout on input field will trigger every time the specific input looses its focus.
But, I want to exclude some specific a tag from triggering that focusout function
Example:
<input type="text" id="name_input">
<a id="apply_name">SAVE</a>
Then the focusout function:
$("#name_input").focusout(function(e) {
//do something here
});
Clicking on "#apply_name" also triggers focusout function of an input. How can I exclude that specific element ID from triggering it.
Note: I tried some tricks already posted on StackOverflow and none of them seams to work...
Another way of doing this is checking what your target id is
var evt;
document.onmousemove = function (e) {
e = e || window.event;
evt = e;
}
$("#name_input").focusout(function (e) {
if (evt.target.id == "apply_name") {
//apply_name clicked
} else {
//focus out and applyname not clicked
}
});
DEMO
You can use "blur" - event.
$("#name_input").on("blur", function(e) {
//your code
});
Solution from How to exclude Id from focusout
Added .hasClass which I also needed:
$('#id').focusout (function (e) {
if (e.relatedTarget && $(e.relatedTarget).hasClass('dontFocusOut')) {
return;
}
//do your thing
});
I have an input field, and on it's focus a note should be seen.
<input type="text" name="contact_email" id="contact_email" onfocus="craateUserJsObject.showContactEmailNote();"/>
<div id="contact_email_note" class="info_box">Contact email note</div>
jQuery code is:
showContactEmailNote : function () {
var ContactEmail = jQuery('#contact_email');
if (typeof ContactEmail.focus(function()
{
{
$("#contact_email_note").show("slow");
}
}
));
if (typeof ContactEmail.focusout(function()
{
{
$("#contact_email_note").hide("slow");
}
}
));
}
The problem is that onfocus event only load the note after the second click on the input field. The same is with onclick event.
How can it load on first focus of the field?
Thanks, Dusan
If you are trying to discover the type of an event, you should use type property of the event object, you are misusing typeof operator, a simple event listener does the trick.
$('#contact_email').on('focus blur', function(event){
$("#contact_email_note").toggle(event.type === 'focus');
})
Use this...
$('#contact_email').on('focus blur', function(){
$("#contact_email_note").toggle("slow");
});
And see this demo
You should use a more easier code like this one :
jQuery
$('#contact_email').focusin(function() {
$("#contact_email_note").show("slow");
}).focusout( function() {
$("#contact_email_note").hide("slow");
});
See working fiddle demo.
Edit to show the note only once
var noteHasBeenShown = false;
$('#contact_email').focusin(function() {
if(!noteHasBeenShown) {
$("#contact_email_note").show("slow");
noteHasBeenShown = true;
}
}).focusout( function() {
$("#contact_email_note").hide("slow");
});
Edit to show the note and don't hide it
$('#contact_email').focusin(function() {
$("#contact_email_note").show("slow");
});