Search code examples
javascriptjqueryfunctionparenttree-traversal

How can a function find a parent element of the anchor which originally called the function?


Ok, the question alone is making my head spin.

I have an anchor tag that is calling a function:

<a href="#" id="addPerson" onClick="addPerson(); return false;">Add a Guest</a>

Just for reference, this is the function that's being called:

function addPerson() {
//current keeps track of how many rows we have.
current++;
console.log($(this).parent('form').attr('id'));
var strToAdd = '<div class="row">\
          <div class="column grid_2">\
            <label for="two-guests-name'+current+'">Guest '+current+':</label>\
          </div>\
          <div class="column grid_5">\
            <input name="two-guests-name'+current+'" type="text" id="two-guests-name'+current+'" value="Name" onfocus="RemoveFormatString(this, \'Name\')" /> \
            <input name="two-guests-age'+current+'" type="text" class="guestage digits" id="two-guests-age'+current+'" value="Age" size="4" maxlength="3" onfocus="RemoveFormatString(this, \'Age\')" />\
          </div>\
        </div>'

$('#numberguests').append(strToAdd)
};

I'd like to allow this function to work on multiple forms on a single page. So my thinking was to travel back in the tree to the parent form element, get its id and use that (somehow) to allow the function to work on multiple forms in the page.

You can see I tried using a quick console.log to test my idea, but it kept coming back "Undefined". I also tried running the console.log in the anchor tag itself, but it also was "Undefined".

I tested .parents() and it works perfectly in the anchor tag, but not in the function iteslf.

Any suggestions?


Solution

  • You should pass $(this) into add parents and then you'll have the proper scope to work with in your function. So:

    <a href="#" id="addPerson" onClick="addPerson($(this)); return false;">Add a Guest</a>
    

    and then in the function use:

    function addPerson(anchorElement) {
        var form = anchorElement.parents("form");
        //etc.
    }