How do I return a value from a jQuery function?
I am trying to return a value from a jQuery function. Here is my function:
$('#output').keypress(function (event){
var keycode = (event.keyCode ? event.keyCode : event.which);
if(keycode == '13'){
var read_lines = $('#output').val().split("\n");
return read_lines[read_lines.length-1];
}
});
and I want to store the return value in another variable
var newRead = functionName(event);
alert (newRead);
How do I do this because I cannot access the function. Thanks in advance!
+3
source to share
2 answers
In event handlers, you must call other functions instead of returning a value. function(){}
there is a function in your event handler callback
.
In your case, you can directly print them in the event keypress
:
$('#output').keypress(function (event){
var keycode = (event.keyCode ? event.keyCode : event.which);
if(keycode == '13'){
var read_lines = $('#output').val().split("\n");
alert(read_lines[read_lines.length-1]);
}
});
Or you can do this:
$('#output').keypress(function (event){
var keycode = (event.keyCode ? event.keyCode : event.which);
if(keycode == '13'){
var read_lines = $('#output').val().split("\n");
MyFunction(read_lines[read_lines.length-1]);
}
});
function MyFunction(result){
alert(result);
}
+2
source to share
To access your read value, you will need a function similar to the one below.
functionName(newRead){
alert(newRead);
}
$('#output').keypress(function (event){
var keycode = (event.keyCode ? event.keyCode : event.which);
if(keycode == '13'){
var read_lines = $('#output').val().split("\n");
functionName(read_lines);
//return read_lines[read_lines.length-1];
}
});
+1
source to share