How to remove a keycode event handler once it has been added? - javascript

How can I remove a keypress event handler after I have set one for an element?
I have a search box with the id #sb that lists search suggestions upon typing via autocomplete, and then goes to the very first suggestion upon pressing enter if there is one.
It works fine if the user enters a search string which does not exist. Pressing ENTER goes nowhere as it should.
However, if a valid search suggestion is returned, and then the user changes their mind and decides to search for another string for which there is no search suggestion... pressing ENTER still goes to the previously suggested search result.
For example, if the user searches for "hot dogs", deletes that entirely, and then searches for "asgdoksadjgoawhet" then upon pressing enter they will be redirected to http://example.com/hot-dogs, when in fact nothing should happen.
Below is the response section of my autocomplete code:
response: function( event, ui ) {
if(typeof ui.content[0] == 'undefined') {
//no search results exist
//make enter do nothing
$('#sb').keypress(function(e) {
if(e.which == 13) {
e.preventDefault(); //does not work
$('#sb').off('keypress', '#sb'); //does not work, either
}
});
} else {
//search results exist
//make ENTER go to the first suggested result
$('#sb').on('keypress', function(e) {
if(e.which == 13) {
window.location.href = 'http://example.com/'+ui.content[0].id;
}
});
}
}
Should I not be using anonymous functions, perhaps?

If you want to unbind it directly after use you can use .one
This will fire the event only once:
$('#sb').one('keypress', function(e) {
if(e.which == 13) {
//do stuff
}
});
If you however want to unbind the event at any other time you can do this:
var kbEvent = $('#sb').on('keypress', function(e) {
if(e.which == 13) {
//do stuff
}
});
.... some other code ...
$('#sb').off(kbEvent);

$( "#foo" ).bind( "click", handler );
function handler(){
//do the stuff
}
//after some condition
$( "#foo" ).unbind( "click", handler );
Bind the reference of function to event callback, so you can later use it to unbind.

$('#sb').on("keypress", function(e) {
if(e.which == 13) {
$(this).off(e);
}
});

$('#sb').off('keypress', '#sb');
removes the event handler on the child elements '#sb' of the element '#sb'.
$('#sb').off('keypress'); removes the event handler on '#sb'.
Another exemple
$( "#dataTable tbody" ).on( "click", "tr", function() {
//...
}); adds an event handler on each tr elements in "#dataTable tbody"
$( "#dataTable tbody" ).off( "click", "tr"); removes it from each tr elements in "#dataTable tbody"

Try this little example it shows you how to bind and unbind an event.
html
<div>
<input id="bind_me"/>
<div>
</div>
</div>
jQuery code
$('#bind_me').on('keypress', function(e)
{
if(e.which==='q'.charCodeAt(0) || e.which==='q'.charCodeAt(0) )
{
$('#bind_me').off('keypress');
}
var tmp = $(this).next().text();
$(this).next().text(tmp+String.fromCharCode(e.which));
});

Related

Why is this my jQuery keypress() event not working?

I have a text box
<input id="textinput" type="text" name="text_input" value=""/>
and a properly linked (did a console.log in the document ready function and it worked) jquery file
$(document).ready(function()
{
console.log("hi");
});
$( '#textinput' ).keypress(function() {
var tag_text = $('#textinput').val();
console.log("key pressed");
});
As far as I can tell, I'm doing everything properly. However, I am obviously not doing something right.
My goal is to make it so that whenever a letter/character (or any key, really) is pressed with focus on the textinput textbox, an event will trigger.
What am I doing wrong here?
Put the keypress function inside the $(document).ready() function:
$(document).ready(function() {
console.log("hi");
$( '#textinput' ).keypress(function() {
var tag_text = $(this).val();
console.log("key pressed");
});
});
JSFiddle
Try binding the keypress event in the $(document).ready() function. Your code works as intended.
$(document).ready(function() {
$( '#textinput' ).keypress(function() {
var tag_text = $('#textinput').val();
console.log("key pressed");
});
});

Jquery .one() function doesn't prevent multi click event during form input

I have a code like that:
$(document).ready(function() {
$("#some-items").one("click", ".comment-form-gonder input", function(e) {
e.preventDefault();
$("body").css("cursor", "wait");
//this part inserts user comment to the written comments below with animation.
...
The problem is when I double click send button, comment are inserted twice. How can I prevent this?
Try removing preventDefault(); and
disable the button to be sure by
$(this).attr('disabled', 'disabled');
var n = 0
$( "div" ).one( "click", function() {
n++;
if (n % 2 == 0){
$(this).text('Foo');
}else{
$(this).text('Bar');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>Foo</div>
Calling e.preventDefault(); within .one() handler, makes the form not able to prevent default behavior after the first type of one('event') is executed. After that, the same event will submit the form as supposed to.
Prevent default form submission using on() and do the rest stuff with one() :
$(document).ready(function(){
$('.comment-form-gonder input[type="submit"]')
.on('click', function(e) {
e.preventDefault();
})
.one('click', function() {
// This part executes only on first click:
$("body").css("cursor", "wait");
// rest of your code...
});
});
JSFiddle
You could also disable the submit input after first click, but in some cases may be desired to keep it 'clickable' (f.ex to inform the user that he cannot submit the form twice). To do so, you could store click state in data attribute of the input and use that state later on:
$(".comment-form-gonder input[type='submit']").on("click", function(e) {
e.preventDefault();
if($(this).data('clicked') == 'clicked'){
return alert('already submitted!');
}
// This part executes only on first click:
$(this).data('clicked', 'clicked');
$("body").css("cursor", "wait");
// rest of your code...
});
JSFiddle

How to disable functionality that takes place after a click event using jQuery

I have a button on my page which, when clicked, listens for another button being clicked and then performs an AJAX call. For example:
$( 'button#a' ).click( function() {
$( 'button#b' ).click( function() {
// Perform an AJAX call here.
});
});
Here is a demo of my code so far:
DEMO
I want to disable the ajax call functionality if a third button button#c is clicked at any time during the time that the page is loaded. I'm at a loss at how this can be done. Hoping someone can suggest an approach.
Should not code click event inside click, but after modifying in your code.
var third_click= false;
$(document).ready(function() {
$( 'button#c' ).click( function() {
third_click = true;
})
$( 'button#a' ).click( function() {
$( 'button#b' ).click( function() {
if( !third_click ) {
// Perform an AJAX call here.
alert( 'ajax call in progress' );
} else {
alert( 'Can\'t call ajax' );
}
});
});
})
here is demo.
What if you used button a to hide button b until a is clicked and then show button b and so fourth until your results are displayed as you with.
example:
$('.btnB').hide();
$('.btnA').on('click', function() {
$('.btnB').toggle();
});
Unless it needs to all display at one time this method wouldn't be able to work in that type of situation
You can just remove the click events from #a and b# when clicking on #c with:
$('#c').click(function () {
$('#a,#b').off('click')
})
jsFiddle example

Popup window not showing div

I have this JQuery code:
function JQueryPopup(value) {
$(value).toggle();
$('#JQueryClose').click(function(){
$(value).hide();
});
$( document ).on( 'click', function ( e ) {
$(value).hide();
});
$( document ).on( 'keydown', function ( e ) {
if ( e.keyCode === 27 ) { // ESC
$(value).hide();
}
});
}
and a HTML button that calls this function, it doesn't seem to be showing the popup window/div.
here is a fiddle with my full code: http://jsfiddle.net/XHLY8/3/
P.S. i do have this code on another page, i call the function like this:
<script type="text/javascript">JQueryPopup('#customer_popup_notes');</script>
which works fine.
You need to add the following:
$('#inbox_button').on('click', function(event){
event.preventDefault(); // This isn't critical, but you would need
event.stopPropagation();
JQueryPopup('#inbox_div');
});
You want to stop the click event from bubbling up and triggering the following:
$( document ).on( 'click', function { ... });
Otherwise your #inbox_div will be hidden before you can see it.
Here is a working fiddle.
I suggest reading up on stopPropagation and preventDefault.
You dont need
$( document ).on( 'click', function ( e ) {
$(value).hide();
});
Which always hides the Bottom div no matter where u click .
Working fiddle

jQuery on "enter key" create content editabledom element and select it

$(document).ready(function(){
$( "p[contenteditable]" ).on( "keypress", function(e) {
var code = e.keyCode;
if(code == 13) { //Enter key
$(this).after('<p class="new" [contenteditable]>hi</p>');
$('p.new').css("color","red").focus();
e.preventDefault();
}
});
});
See this fiddle: http://jsfiddle.net/tehtrav/T2U9M/
I'm trying to create a new <p contenteditable></p> when the enter key is pressed and change focus to it, but the focus doesn't seem to trigger. It works if I set the focus to an element other than the new paragraph (see this fiddle), but not if I call focus on the newly created paragraph.
Any ideas?
When I use your code but take the brackets our of the creation of the new paragraph, it works
$(document).ready(function(){
$( "p[contenteditable]" ).on( "keypress", function(e) {
var code = e.keyCode;
if(code == 13) { //Enter key
$(this).after('<p class="new" contenteditable>hi</p>');
$('p.new').css("color","red").focus();
e.preventDefault();
}
});
});

Categories

Resources