treehouse : what would you like to learn today?
Web Design Web Development iOS Development

jQuery: Traversing up, over and down

  • I've got several forms on one page and I want to validate whether or not one of the fields on the form that is being submitted is filled in or not.

    Basically my form looks like this:


    <form action='' method='post'>
    <table>
    <tr>
    <th>White Shirt</th>
    </tr>
    <tr><td>Quantity: <input type='text' class='quantity' name='quantity' size='1'/></td></tr>
    <td>Price: <strong>$29</strong></td></tr>
    </table><br/>
    <input type='submit' onclick='checkform()' value='Request' name='submit'>
    </form>


    So my thought process was, select THIS, which would be the submit button, then use closest() to go up the tree to the table, then go back down to .quantity, and get the value of that.


    function checkform() {
    alert($(this).closest('table').children('.quantity').val());
    }


    Unfortunately, the only thing I'm getting is "undefined". What's the proper way to traverse to get what I'm looking for?
  • Try:
    function checkform() {
    alert($(this).closest('table').find('.quantity').val());
    }
  • That didn't work.

    I also thought about changing it to .closest('form'), since table is on the same level as the submit button, but that didn't make any difference. I also tried it with the .find() that you suggested, and still no luck.

    Any other suggestions?