jQuery - bind multiple events and exclude other events - javascript

I've got a search form that has both <input type="text"> and <select> form elements. Listening in to that form I've got this jQuery...
$('#searchform :input').stop().on('keyup change',function(){
// do some ajax stuff
})
The tricksy bit is the way the script listens for multiple events using .on('keyup change' etc.). This works great but there's a problem...
When the input fields lose focus the script jquery listener is triggered.
Here's a demonstration to explain what I mean https://jsfiddle.net/o2k4jf90/1/
I want to do something like this...
$('#searchform :input').stop().on('keyup change not:blur',function(){
// do some ajax stuff
})
...but clearly that's nonsense. What can I do?

Try substituting input event for change , keyup events
$(document).ready(function () {
$(':input').on('input',function(e) {
$('#report').append('stuff happened<br />');
})
});
jsfiddle https://jsfiddle.net/o2k4jf90/3/

The issue is because the change event fires when an input field loses focus, and when the chosen option of a select is modified. To achieve what you need, you would need to bind the events separately. Try this:
$(document).ready(function () {
$('input').keyup(stuffHappened);
$('select').change(stuffHappened);
})
function stuffHappened() {
$('#report').append('stuff happened<br />');
}
Updated fiddle
You can still use a single event handler if you hook the event to the form, however you would need to check the type and target.tagName of the event to achieve the same logic, which is not pretty at all:
$('form').on('keyup change', function(e) {
if ((e.type == 'change' && e.target.tagName == 'SELECT')
|| (e.type == 'keyup' && e.target.tagName == 'INPUT')) {
$('#report').append('stuff happened<br />');
}
});
For this reason, I would suggest using the former method.

Related

jquery bind form submission and anchor in single call

Currently I have this code (which works just fine):
<form>
<input type="text" />
<a id="btn">add</a>
</form>
$(document).ready(function () {
$('form').submit(foo);
$('#btn').click(foo);
});
function foo() {
//do some stuff
}
I am currently binding the foo function to both the form submission, and the anchor click. But, I actually prefer not to have the form, although it seems to be the easiest way to bind the enter key on the textbox to the foo function.
What is the easiest way to achieve both bindings in one single statement, without the form, and without binding the textbox to a keypress and checking the keycode == 13? Is there a built in event I can bind to for the enter key on the textbox?
To explain with some pseudo code, this is roughly what I would like it to look like:
//get rid of the form
<input type="text" class="submit"/>
add
$(document).ready(function () {
//and only have one binding statement
$('.submit').bind('click enterPressed', foo);
});
function foo() {
//do some stuff
}
There's no ready-made event called enterPressed or any event for that matter that just responds to the enter key. The short answer is, therefore, there's no way to achieve what you've asked. The long answer is below, if you're open to creating a custom event, enterPressed.
You can define a custom event called enterPressed on the input element, and then you would have to prevent the input element from responding to any click events:
$(function() {
$('input.submit').on('keypress', function(e) {
e.which !== 13 || $(this).trigger( 'enterPressed' );
})
.on('click',function(e) { e.stopImmediatePropagation(); });
$('.submit').on('click enterPressed', foo);
function foo() {
console.log( 'foo called' );
}
});
WORKING JS FIDDLE DEMO
For your enterPressed event you can do this. Trigger your custom event:
$('#element').keyup(function(event) {
if(event.which === 13) $('#element').trigger('enterPressed');
});
You can use .on() to bind a function to multiple events including the custom one:
$('#element').on('click enterPressed', function() {
...
});
Not sure about the code. But it should give you something to look up.

Change event type

I'm trying to get the type of change of an element.
<input type="text" onchange="fn()"/>
<script>
function fn() {
if (event.isKeyPress)
// do something
else if (event.isClick)
//do something else
</script>
So in full, I'm changing a text field, then to change, the user has to unfocus the field and change its contents. I want to find the manner at which it was unfocused (e.g. by tab or click). Is this possible?
NOTE:
I am using jQuery.
If you put a keydown event on your input, you can trig the focusout event if the pressed key is "tab" and do what you want.
Else the focusout will be triggered by a clic.
You can use Keydown. See: http://www.javascripter.net/faq/onkeydown.htm or http://www.w3schools.com/jsref/event_onkeydown.asp
$('input').focus(function(){
// something..
}).change(function(){ // or keyup
// do something awesome
}).focusout(function(){
// that's it
});
$( "input" ).focusout(function() {
// do something
})
http://api.jquery.com/focusout/
https://api.jquery.com/focusin/
http://api.jquery.com/focus/

onblur doesn't work when i clone input

I want to change input type text to password. But it doesn't work in ie8. I found a solution; clone and replace input but onblur doesn't work after clone.
The debugger doesn't break OnBlur function. Can somebody show me?
Here is js code :
$(document).ready(function () {
var input = document.getElementById("Password");
var input2 = input.cloneNode(false);
input2.id = 'password1';
input2.type = 'password';
$('#Password').focus(function () {
input.parentNode.replaceChild(input2, input);
input2.focus();
});
$('#password1').blur(function () {
if ($(this).val() == '' || $(this).val() == Passwordtxt) {
document.getElementById("password1").setAttribute("type", "text");
$(this).val(Passwordtxt);
}
});
});
Change
$('#password1').blur(function () {
to
$('body').on('focusout','#password1',function () {
See .on()
The focus and blur events are specified by the W3C to not bubble, but jQuery defines cross-browser focusin and focusout events that do bubble. When focus and blur are used to attach delegated event handlers, jQuery maps the names and delivers them as focusin and focusout respectively. For consistency and clarity, use the bubbling event type names.
use on event delegate
try this
$(document).on('blur','#password1',function () {...
replacing the document with the closest element is preffered

Jquery : how to trigger an event when the user clear a textbox

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" />

jQuery trigger not working in IE. Why?

$('#XynBp0').find('input').each(function(){
if ($(this).attr('value') == 'Cancel'){
$(this).trigger('click');
}
});
doesn't work in IE7
it's strange but try to create a custom event
$('#XynBp0 input').bind('custom',function(){
//code
})
$('#XynBp0').find('input').each(function(){
if ($(this).attr('value') == 'Cancel'){
$(this).trigger('custom');
}
});
Does this work?
$.click() (or $.trigger('click')) doesn't simulate a mouse click; it fires off any onclick events bound to that element. If you haven't assigned an onclick event to that input you're searching for, nothing will happen.
It sounds like you're trying to submit the form with a traditional submit button (e.g. <input type="submit" value="Cancel">). If that's the case, you may have to use $(yourform).submit() to submit the form, in combination with some handling of the data sent to the server to simulate clicking the Cancel button.
Is it wrapped in a dom ready event? Might help if you provide more code.
$(function () {
$('#XynBp0').find('input').each(function () {
if ($(this).attr('value') == 'Cancel') {
$(this).trigger('click');
}
});
});
Your code snippit doesn't make any sense, you are clicking inputs if they are canceled?
Here's some things to clean up in your code
$('input','#XynBp0').each(function () {
var $this = $(this);
if ( this.value === 'Cancel' ) { //Don't need jQuery here
$this.trigger('click'); //Probably don't need it here either
}
});
What does click even do? If you are trying to submit a form, use form.submit();

Categories

Resources