1

I'm trying to get the value of an form input, which is inside a table cell, but it is getting returned as undefined.

$('.js-form').submit(function(event) {
        alert($(this).children().has("input[name='points']").val());
});

My HTML is as follows:

<tr>
<form action='...' method='post' class='js-form'>
    <td><input type='text' name='points'/></td>
</form>
</tr>

There are multiple of these forms on the same page, I'm under the impression that using $(this) will restrict my DOM traversal to the selected form that the function is currently handling, but not sure why I don't get any value back? (there is a value in the field)

3
  • 3
    In the best case, you are trying to get the value from the td element. Have a look at the documentation: api.jquery.com/has. However, your HTML is invalid and the browser might actually render a totally different DOM (e.g. move the form out of the row). Commented Sep 7, 2014 at 18:05
  • alert(("input[name='points']); Commented Sep 7, 2014 at 18:12
  • @johnSmith That line you posted will cause a syntax error, and it would just alert the literal string if it didn't. Also, there may be more than one input[nqme='points'] which would explain why OP is seeking from the form itself. Commented Sep 7, 2014 at 18:16

1 Answer 1

1

Use .find()

alert( $(this).find("input[name='points']").val() );

There is a problem with your HTML though; You can't nest a form between a tr and a td. http://www.w3.org/TR/html401/struct/tables.html#h-11.2.5

This could mean the browser renders your code differently to what you expect. These are both acceptable structures:

<form action='...' method='post' class='js-form'>
    <table>
        <tr>
            <td><input type='text' name='points'/></td>
        </tr>
    </table>
</form>

<table>
    <tr>
        <td>
            <form action='...' method='post' class='js-form'>
                <input type='text' name='points'/>
            </form>
        </td>
    </tr>
</table>
Sign up to request clarification or add additional context in comments.

6 Comments

@a7omiton: You also mentioned "nested form." One <form> should not be nested within another; that's also invalid HTML structure. See stackoverflow.com/questions/379610/can-you-nest-html-forms
Good observation. Have you nested a form inside a form @a7omiton ?
oh no, i don't have a nested form, when i said that i was just referring to the form inside the table
@Popnoodles in the second acceptable structure you mentioned <tr> <td> <form> <input>, but that stores everything in one cell?
Based on the code given, "everything" is one input field. You can't mix table structure with other elements. You need to work around that restriction.
|

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.