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

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

Related

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

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

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

Triggering datepicker from function doesnt work

I use a pickadate.js plugin.
What i would like to do is to trigger a date container after checkbox is checked, but it somehow doesn't work. I assume it has to do something with out of the scope variables since it works just fine outside the checkbox event function.
Official documentation:
See here and also here
JS:
var pick = $('#chosen').pickadate({format:'dd.mm.yyyy'});
var picker = pick.pickadate('picker');
//picker.open();
// it works here
$(":checkbox").change(function() {
if(this.checked) {
picker.open();
// it doesnt work here
event.stopPropagation();
console.log('checkbox triggers!');
}
});
JSFIDDLE
Use .on() with click. (like (.on("event", fn)))
$(":checkbox").on('click', function () {
if (this.checked) {
picker.open();
event.stopPropagation();
}
});
Fiddle
I used trigger method and now I think it works as intended:
$( "input[type=checkbox]" ).on( "click", function(){
$(":checkbox").trigger("change");
} );
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();
}
});
});

Javascript disable onclick event until it's event is finished

How can I temporary disable onclick event until the event is finished?
So far that's all I've come up with:
<script>
function foStuff(a){
//no modifications here to be done, just some code going on
}
$(document).ready(function(){
$("#btn").click(function(){
var obj = $(this);
var action = obj.prop('onclick');
obj.prop('onclick','');
whenDoStuffFinishes.(function(){ //when do stuff finishes is what i need to get
obj.prop('onclick',action);
});
});
});
</script>
<div id="btn" onclick="doStuff(500)">
</div>
EDIT:
I've tried it this way: but it doesn't unblock the click event
$("#btn").click(function(){
var obj = $(this);
obj.off('click');
$.when( doStuff(500) ).then( function(){
obj.on('click'); // it actually comes here, but click event is being unset
} );
});
<script>
$(document).ready(function(){});
</script>
<div id="btn">
</div>
Well, you can create a variable that tells your function to ignore it while it's true;
var isIgnore = false;
$("#btn").click(function(){
if(isIgnore)
return;
isIgnore = true;
var obj = $(this);
var action = obj.prop('onclick');
obj.prop('onclick','');
whenDoStuffFinishes.(function(){
obj.prop('onclick',action);
isIgnore = false;
});
});
This code is not tested but I think this will work.
Simply reference the handler, and detach it before performing your action, then at the end attach it again ...
$(document).ready(function () {
var handler = function () {
var obj = $(this);
obj.off('click');
whenDoStuffFinishes.(function () {
obj.click(handler);
});
};
$("#btn").click(handler);
});
use pointerEvents.try this:
$("#btn").click(function(){
document.getElementById('btn').style.pointerEvents = 'none';
whenDoStuffFinishes.(function(){
document.getElementById('id').style.pointerEvents = 'auto';
});
});
Using a combination of bind and unbind
https://api.jquery.com/bind/
https://api.jquery.com/unbind/
Turn the event off once it is triggered and reattach it at the end of the callback.
jQuery( '#selector' ).on( 'click', function voodoo( event ) {
jQuery( event.target ).off( event.type );
// Do voodoo...
jQuery( event.target ).on( event.type, voodoo );
});
Alternatively and depending on the scenario, event.stopImmediatePropagation() might also serve as a solution. It will stop all subsequently attached event handlers from firing and itself from bubbling up the DOM tree.
jQuery( '#selector' ).on( 'click', function( event ) {
event.stopImmediatePropagation();
});

Categories

Resources