1

I am trying to write a simple function to avoid replication of code and return a value from an input but when I try to return it via the function i just get "undefined".

Any ideas why?

function get_selected_id() {
    return $(this).parents("tr").find("input[name*=page_id]").val();
}

$("a").click( function(e) {
    e.preventDefault();
    alert(get_selected_id()); // RETURNS UNDEFINED
    alert($(this).parents("tr").find("input[name*=page_id]").val()); // RETURNS 123
});

html (very simplified):

<table>
    <tr>
        <td>page id <input type="hidden" value="123" name="page_id[]" /></td>
        <td><a href="#">Click</a></td>
    </tr>
</table>
0

2 Answers 2

1

You don't pass the value to get_selected_id(). So when the function tries to return $(this) it is undefined because it can't match any element. You have to pass as argument the element that is clicked!

Try

function get_selected_id(e) {
    return e.parents("tr").find("input[name*=page_id]").val();
}

$("a").click( function(e) {
    e.preventDefault();
    alert(get_selected_id($(this))); // RETURNS 123
    alert($(this).parents("tr").find("input[name*=page_id]").val()); // RETURNS 123
});

DEMO

Sign up to request clarification or add additional context in comments.

Comments

0

this keyword in javascript is context-dependent.

Try to pass $(this) as argument to your function:

function get_selected_id(obj) {
    return obj.parents("tr").find("input[name*=page_id]").val();
}

alert(get_selected_id($(this)));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.