How to Bind keyup event to jQuery plugin - javascript

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

Related

Onlick event not triggering which contains blur function

I have a form and on click on an input, I'm adding classes to that input's wrapped div.
To do this, I've made use of blur and executing my function on click. However, on some cases (very rarely) it will work (and add the class). But majority of the time, it doesn't perform the click action (because the console.log("click") doesn't appear).
My thinking is that maybe the browser is conflicting between the blur and click. I have also tried changing click to focus, but still the same results.
Demo:
$(function() {
var input_field = $("form .input-wrapper input");
$("form .input-wrapper").addClass("noData");
function checkInputHasValue() {
$(input_field).on('blur', function(e) {
var value = $(this).val();
if (value) {
$(this).parent().closest(".input-wrapper").removeClass("hasData noData").addClass("hasData");
} else {
$(this).parent().closest(".input-wrapper").removeClass("hasData noData").addClass("noData");
}
});
}
$(input_field).click(function() {
checkInputHasValue();
console.log("click");
});
});
i've done some modification in your code .
function checkInputHasValue(e) {
var value = $(e).val()
if (value) {
$(e).parent().closest(".input-wrapper").removeClass("hasData noData").addClass("hasData");
} else {
$(e).parent().closest(".input-wrapper").removeClass("hasData noData").addClass("noData");
}
}
$(document).on('blur',input_field, function(e) {
checkInputHasValue($(this));
});
$(document).on("click",input_field,function() {
checkInputHasValue($(this));
console.log("click");
});
In order to avoid conflits between events, you would separate the events and your value check. In your code, the blur event may occur multiple times.
The following code seems ok, as far as I can tell ^^
$(function() {
var input_field = $("form .input-wrapper input");
$("form .input-wrapper").addClass("noData");
function checkInputHasValue(el) {
let target = $(el).closest(".input-wrapper");
var value = $(el).val();
$(target).removeClass("hasData noData");
$(target).addClass(value.length == 0 ? "noData" : "hasData");
console.log("hasData ?", $(target).hasClass("hasData"));
}
$(input_field).on("click", function() {
console.log("click");
checkInputHasValue(this);
});
$(input_field).on("blur", function() {
checkInputHasValue(this);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<div class="input-wrapper">
<input>
</div>
</form>

What event is triggered when the value of an input field is changed?

I'm using a JavaScript library that occasionally changes the value of an input field. I want to detect when that happens.
Apparently, the change and input events are not triggered when the value of an input field is changed (at least not on Chrome).
To verify that, I have tried this (using jQuery):
<script>
$(function() {
$('#inp').on('change',function() { console.log('change event'); });
$('#inp').on('input',function() { console.log('input event'); });
$('#inp').val('hello');
});
</script>
<input type="text" id="inp">
Neither the change event nor the input event is triggered when I call .val('hello').
How can I detect the change? (Please remember that the code that changes the value is outside my control, so I cannot add a call to trigger() there.)
There is a work around, you can pool the value of textbox after regular intervals and trigger the event when it is changed.
Live Demo
$('#elementId').change(function(){
alert("changed");
});
var previousVal = "";
function InputChangeListener()
{
if($('#elementId').val() != previousVal)
{
previousVal = $('#elementId').val();
$('#elementId').change();
}
}
setInterval(InputChangeListener, 500);
$('#elementId').val(3);
Edit based on comments for many elements.
You can use array and monitor, 30 element wont be a performance concern
Live Demo
$('.someclass').change(function(){
alert("changed, id >> " + this.id);
});
var hashTablePrevElem=[];
$('.someclass').each(function(){
hashTablePrevElem[this.id] = this.value;
});
function InputChangeListener()
{
$('.someclass').each(function(){
if(hashTablePrevElem[this.id] != this.value)
{
hashTablePrevElem[this.id] = this.value;
$(this).change();
}
});
}

Intercept value changes within .blur() event

I'm using .blur() function to execute some code every time a text field loses focus (also when its value doesn't change).
Now I need to add some logic that must be executed only when text field value changes. Is there a way to combine .change() event with .blur()? Or, better, is there a way to know if the value in my text field is changed just using .blur()?
Not directly, but you can store the value on focus event..
something like
$('input')
.on('focus',function(){
// store the value on focus
$(this).data('originalValue', this.value);
})
.on('blur',function(){
// retrieve the original value
var original = $(this).data('originalValue');
// and compare to the current one
if (original !== this.value){
// do what you want
}
});
Of course you could just bind different handlers for each event..
$('input')
.on('change', function(){/*your change code*/})
.on('blur', function(){/*your blur code*/});
The event change is trigger every time that the field lose the focus and the content has change. I think what you need is to use change() instead of blur(). Take a look at this jsfiddle
$('#in').change(function(){
alert('change!');
});
If what you need is to execute the same code when the input loses the focus and when the value changes, you can combine both events
$('in').on('change blur', function(){
//code
});
you can use closure to store the previous value and compare them later
var createOnBlurFunc = function(){
var prevVal = '';
return function(e){
if(prevVal === $(this).val()){
//same value
} else {
prevVal = $(this).val();
// do something
}
}
};
$('input').blur(createOnBlurFunc());
I think this is a more generalized way, for those that are created on the fly:
var $bodyEl = $('body'), inputOldValue;
$bodyEl.on('focus', 'input, textarea, select', function () {
inputOldValue = $(this).val();
});
$bodyEl.on('blur', 'input, textarea, select', function () {
if (inputOldValue != $(this).val()) {
$(this).trigger('changeBlur');
}
});
input, textarea, select is faster than :input as a selector.

onfocus fires after second click time

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");
});

Simulate an "ontype" event

I want to simulate the Google Search effect that even with the search box not focused, the user can start typing and the input box will capture all keyboard strokes.
I have looked for an ontype event, but haven't found anything. I know that the event object in callbacks for events like click has keyboard information, but I don't think this is what I'm after.
This does the job:
$(document).on('keydown', function() {
$('input').focus();
});
HTML:
<input type="text" id="txtSearch" />
Javascript:
var googleLikeKeyCapture = {
inputField : null,
documentKeydown: function(event) {
var inputField = googleLikeKeyCapture.inputField;
if(event.target != inputField.get(0)) {
event.target = inputField.get(0);
inputField.focus();
}
},
init: function() {
googleLikeKeyCapture.inputField = $('#txtSearch');
$(document).bind('keydown', googleLikeKeyCapture.documentKeydown);
googleLikeKeyCapture.inputField
.focus(function() {
$(document).unbind('keydown');
})
.blur(function() {
$(document).bind('keydown', googleLikeKeyCapture.documentKeydown);
});
googleLikeKeyCapture.init = function() {};
}
};
$(googleLikeKeyCapture.init);
Also you can find jsFiddle example here
EDIT :
And now it's a jQuery plugin. :) If keydown occures in a textarea or input field it doesn't capture keys, anything else goes to designated input field. If your selector matches more than one element it only uses the first element.
Usage: $('#txtSearch').captureKeys();
The event you are after is onkeypress.
Try this jQuery Text Change Event plugin:
http://www.zurb.com/playground/jquery-text-change-custom-event

Categories