How to pass "this" on an enter key event? - javascript

I think this is a syntax question, but I can't seem to find a question that answers what I'm looking for. There's lots that are... close. Might be something with binding, or "apply", but I can't figure out how to use those in this context.
I have a function, that when fired, turns a span into an input so it can be edited. Then, when the focus is off (blur), the new text is saved. So far that works exactly as I wanted. I thought it would be nice if enter key would do the same thing... but I can't figure out how to make the event work.
function span_into_textarea() {
var old_text = $(this).text();
var editableText = $("<input type='text' />");
editableText.val(old_text);
$(this).replaceWith(editableText);
editableText.focus();
editableText.blur(textarea_into_span);
editableText.keypress(function (e) {
if (e.which == 13) {textarea_into_span()}
}); // THIS DOESNT PASS ANYTHING TO "THIS"
editableText.keypress(textarea_into_span); //THIS WORKS BUT I CAN'T KNOW WHICH KEY WAS PRESSED
}
function textarea_into_span() {
var new_text = $(this).val();
}
Thanks for any help!

You can use call to pass the this reference:
editableText.keypress(function (e) {
if (e.which == 13) {textarea_into_span.call(this)} //will refer to editableText
});

You may bind: editableText.keypress( textarea_into_span.bind(this) ) (event is passed as an argument).
You may replace textarea_into_span with an arrow function (they don't bind this so it is looked up in parent context):
editableText.keypress( (e) => {
if (e.which == 13) {
var new_text = $(this).val();
}
})
As suggested by #Mouser you may use call or apply:
editableText.keypress( function(e) {
if (e.which == 13) {
textarea_into_span.call(this);
// or textarea_into_span.apply(this)
}
})

Try this way, you were losing the scope:
function span_into_textarea() {
var modify = this;
var old_text = $(this).text();
var editableText = $("<input type='text' />");
editableText.val(old_text);
$(this).replaceWith(editableText);
editableText.focus();
editableText.blur(textarea_into_span(modify));
editableText.keypress(function (e) {
if (e.which == 13) {textarea_into_span(modify)}
});
}
function textarea_into_span(modify) {
var new_text = $(modify).val();
}

editableText.keypress(function(e) {
var key = e.which;
if (key == 13) // enter key ascii code
{
textarea_into_span.call(this) //will refer to editableText
}
});

Related

How to save the value of an input for a function?

I'm new to PHP and SQL and JQUERY/JS. I'm trying to make is so that when a person press's enter(while in an input field) the same thing occurs as if they hit the existing button.
This is the original button code:
$(document).on("click", '.submit', function(event) {
var to_user_id = $(this).attr('id');
to_user_id = to_user_id.replace(/chatButton/g, "");
sendMessage(to_user_id);
});
My Attempt at making it so that enter did the same thing as the above code:
$('#chatMessage3').keyup(function(e) {
if (e.keyCode == 13) {
var to_user_id = $(this).attr('id');
sendMessage(to_user_id);
}
It looks like your submit buttons have IDs like chatButton1, chatButton2, etc. and you want to just send 1, 2. You need to do a similar replacement in the #chatMessage3 handler:
$('#chatMessage3').keyup(function(e) {
if (e.keyCode == 13) {
var to_user_id = $(this).attr('id');
to_user_id = to_user_id.replace(/chatMessage/, '');
sendMessage(to_user_id);
}

JAVASCRIPT - intercepting keycode 13 (enter) in dynamically-created editbox and passing element to different function

Ok..I've been working all day on a demo CRUD app learning some Bootstrap and JS basics...
I've almost got what I want but the last thing is I need it to do is while in the editbox to grab the keycode 13 event (enter) and so send the right class to a function that already works..
it all goes something like this...
$(function() {
...
...
$(document).on("blur", "input#editbox", function(){ saveEditable(this) });
});
function saveEditable(element) {
$('#indicator').show();
var User = new Object();
User.id = $('.current').attr('user_id');
User.field = $('.current').attr('field');
User.newvalue = $(element).val();
var userJson = JSON.stringify(User);
$.post('Controller.php',
{
action: 'update_field_data',
user: userJson
},
function(data, textStatus) {
$('td.current').html($(element).val());
$('.current').removeClass('current');
$('#indicator').hide();
},
"json"
);
}
function makeEditable(element) {
$(element).html('<input id="editbox" size="'+ $(element).text().length +'" type="text" value="'+ $(element).text() +'" onkeypress="return checkForEnter(event)">');
$('#editbox').focus();
$(element).addClass('current');
}
function checkForEnter(e){
if (e.keyCode == 13) {
saveEditable(e);
return false;
}
}
It works pretty good on the blur event firing but just isn't quite there for ENTER
here is the link...just Load the table and see http://markenriquez.tekcities.com/credapp
advTHNAKSance
You are passing event as argument to saveEditable() method from checkForEnter(). Wherein you should pass input field reference instead.
Try this,
function checkForEnter(e){
if (e.keyCode == 13) {
saveEditable(e.target);
return false;
}
}
Hope this helps.
$(window).on("keypress", "input#editbox",function(e){
if(e.keyCode == 13){
do_something();
}
});
PS. Your textarea top-left and bottom-left corners are rounded.

Create variable to a path JSON is an action performed by jQuery

Need to load the "summary" of each item are all together starting from a JSON.
I created this variable but this seems wrong because I always returns the first item, not the current item.
javascript:
// it seems to be wrong
var description = json.query.results.channel.item.map(function (item) {
return item.summary;
});
var i = 0;
$(".selected").each(function () {
if ($(this).css("background") == "red") i = $(this).index();
});
JSFIDDLE
// Call Ajax Key Enter
$(document).on('keypress', function (e) {
if (e.which == 13) {
$('.description').html(description[$(".selected").index()]);
}
e.preventDefault();
});
try this modification http://jsfiddle.net/2NmnB/4/
$(document).on('keypress', function (e) {
if (e.which == 13) {
var x = $('li').index( $('.selected'));
$('.description').html(description[x]);
}
e.preventDefault();
});

Javascript character restriction and calling a function with getElementById

I have a JS function that checks and restricts certain characters typed in input forms.
The code look like this:
var alphaOnly = /[sA-Za-z\söÖäÄüÜ]/g;
var alphaextraOnly = /[A-Za-z\-&/'"\öÖäÄüÜ]/g;
var alphadigitsOnly = /[sA-Za-z\söÖäÄüÜ\s1234567890]/g;
var digitsOnly = /[1234567890]/g;
var integerOnly = /[0-9\.]/g;
var mailOnly = /[a-z\.#]/g;
function restrictCharacters(myfield, e, restrictionType) {
if (!e) var e = window.event
if (e.keyCode) code = e.keyCode;
else if (e.which) code = e.which;
var character = String.fromCharCode(code);
// if they pressed esc... remove focus from field...
if (code==27) { this.blur(); return false; }
// ignore if they are press other keys
// strange because code: 39 is the down key AND ' key...
// and DEL also equals .
if (!e.ctrlKey && code!=9 && code!=8 && code!=36 && code!=37 && code!=38 && (code!=39 || (code==39 && character=="'")) && code!=40) {
if (character.match(restrictionType)) {
return true;
} else {
return false;
}
}
}
It works when I add onkeypress to input like this:
<input type="text" class="span4 register_input" id="firma" name="firma" onkeypress="return restrictCharacters(this, event, alphaOnly);" />
But I want to do that with getElementById in the script. I tried to add this:
window.onload = function() {
document.getElementById("firma").onkeypress = restrictCharacters(this, event, alphaOnly);
}
But it didn't work... Help please.
You can't pass the arguments like that to onkeypress you would need to use a wrapper function
document.getElementById("firma").onkeypress = function (e)
{
return restrictCharacters(this,e,alphaOnly);
};
jsFiddle http://jsfiddle.net/BjU2e/5/
You are assigning to onkeypress the result of restrictCharacters(this,event,alphaOnly) instead of a function delegate. A correct version is in the following jsFiddle : http://jsfiddle.net/xL47r/1/
For future reference :
document.getElementById("firma2").onkeypress = function(e) {
return restrictCharacters(this,e,alphaOnly);
};
You can get this from e.target
document.getElementById("firma").onkeypress = function(e) {
restrictCharacters(e.target,e,alphaOnly);
}
document.getElementById("firma").onkeypress = function(){
return restrictCharacters.call(this/*becauseof 'this.blur()' */, this,event,alphaOnly);
};
You have wrong syntex to bind event with dom .here it is : window.onload = function () {
var ab = document.getElementById("firma");
ab.setAttribute("onkeypress", "restrictCharacters(this,event, true)");
}

How to find out user pressed "enter" in text input?

I'm trying to add text input's element to my array when user pressed enter key. but I don't know how to do that. I tried this if statements but they didn't work:
var val = $("#txbxfeeds").val();
if (val[val.length-1] == "\r") {
alert("HI");
}
if (val[val.length-1] == "\n") {
alert("HI");
}
How can I do this?
I can suggest the following:
var vals = [];
$("#txbxfeeds").on("keypress", function(e) {
if (e.which == 13) {
vals.push(this.value);
}
});
DEMO: http://jsfiddle.net/Q4CUf/
$("#txbxfeeds").on('keyup', function(e) {
//13 is the code for enter button
var val = $(this).val(); // or this.value
if(e.which == 13) {
alert( val );
}
});
Working sample
Read more about jQuery event.which

Categories