orsina
orsina

Reputation: 131

How to return value from jQuery function?

I am trying to return value from 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 save the value it return in another variable

var newRead = functionName(event);
alert (newRead);

How can I do this because I am not able to access function. Thanks in advance!

Upvotes: 3

Views: 2535

Answers (2)

ashokd
ashokd

Reputation: 393

In order to access your read value, you need function similar as 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];

    } 
    });

Upvotes: 1

renakre
renakre

Reputation: 8291

In event handlers, you should call other functions instead of returning a value. function(){} in your event handler is a callback function.

In your case, you can directly print them in the keypress event:

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

Upvotes: 2

Related Questions