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

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

Related

Textarea resize JS script bug

I'm trying to fix a bug in the JavaScript I wrote to resize the <textarea> of my form.
I want it to resize based on the number of text lines. Ideally, the bottom line should follow.
Form link: LorenzoMengolini.com/contact
<script>
(function($) {
var span = $('<span>').css('display','inline-block')
.css('word-break','break-all').appendTo('body').css('visibility','hidden');
function initSpan(textarea){
span.text(textarea.text())
.width(textarea.width())
.css('font',textarea.css('font'));
}
$('textarea').on({
input: function(){
var text = $(this).val();
span.text(text);
$(this).height(text ? span.height() : '1.1em');
},
focus: function(){
initSpan($(this));
},
keypress: function(e){
if(e.which == 13) e.preventDefault();
}
});
})(jQuery);
</script>
Isn't this code better than a javascript function?
<textarea name="text" oninput='this.style.height = "";this.style.height = this.scrollHeight + "px"'></textarea>

Block event change if click inside or outside the input

i have some problem how to block event change if click inside or outside the input.
<input type="number" id="tenure-long" value="2" min="1" max="10" />
$( document ).on( 'keyup change', '#tenure-long', function( e ) {
// fire function
});
// try block with this, but not working
$( document ).on( 'click', 'body', function(event){
event.preventDefault();
event.stopPropagation();
});
I want, if user after change input value and click on other element of page don't fire change event again.
You can try this:
$(document).on( 'click', 'body', function(event){
if (event.target.id !== 'ternure-log') {
$('#tenure-long').attr('disabled','disabled')
}
});
If you click somewhere else you can disable your input in this way won't be possible change it's value again.
Here you have a live demo.

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

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

Show hidden detail when clicking enter in footable

I am trying to apply some simple functionality to a footable. I have a footable were you can tab through the rows. At each row I wish to be able to click enter to expand hidden content/details for the current selected row, but I am having some trouble locating the click function and adding keypress enter.
This is currently some jquery that i have added, but this won't work simply because the HTML is render from javascript, meaning that the hidden content is not render before i click on the row with the mouse:
$("tbody").delegate("*", "focus blur", function () {
var elem = $(this);
setTimeout(function () {
elem.toggleClass("focused", elem.is(":focus"));
}, 0);
});
$('.footable > tbody > tr').keypress(function (e) {
if ($(this).hasClass("focused") && e.which == '13') {
//alert('test');
$('.footable-row-detail').css({ "display": "table-row" });
}
});
As per your first example, use a delegated event handler for the keypress event too:
$('.footable > tbody').on('keypress', '> tr', function (e) {
if ($(this).hasClass("focused") && e.which == '13') {
//alert('test');
$('.footable-row-detail').css({ "display": "table-row" });
}
});
So long as the .footable table element exists always, the events bubble up to the event handler there. Then the '> tr' selector is applied to the element in the bubble-chain. That means the row only has to match at event time.
If the footable table itself is dynamic, move up the ancestors to something more permanent. document is the default if nothing else is closer/convenient (never use body for delegated events as it has a bug caused by styling):
$(document).on('keypress', '.footable > tbody > tr', function (e) {
if ($(this).hasClass("focused") && e.which == '13') {
//alert('test');
$('.footable-row-detail').css({ "display": "table-row" });
}
});
Found out what the problem was.
$table.find(opt.toggleSelector).unbind('keypress').keypress(function (e) {
if ($(this).hasClass('focused') && e.which == 13) {
//alert('You pressed enter!');
$(this).trigger(trg.toggleRow);
}
});

Categories

Resources