jQuery to get value of textbox

gemini6609 picture gemini6609 · Feb 26, 2014 · Viewed 11.8k times · Source

I need to write some jQuery/javascript to do some validation before submitting a form, because I have to check per some very specific results. Per my tests I believe I am accessing the correct row of data as $(this) in my table with my validation tests, however I cannot get the value typed into the text box of the second td of the row. Something is incorrect with:

alert($(this).closest('td').find($("input[name=test]")).val())

which is preventing the jQuery from getting the value typed into the test textbox of the html below.

<tr>
<td>
    <select id="selectId3" name="selectId3" data-val-required="The selectId3 field is required." data-val-number="The field selectId3 must be a number." data-val="true">
        <option value="">-- Select Area --</option>
        <option value="2">2</option>
        <option value="6">6</option>
        <option value="7">7</option>
        <option value="10">10</option>
        <option value="13">13</option>
        <option value="16">16</option>
        <option value="17">17</option>
    </select>
</td>
<td>
    <span style="label2">
        <input id="test" type="text" value="" name="test">
    </span>
</td>
<td>   </td>

$('#myForm').submit(function () {
    $("select").each(function () {
        if (($(this).val() != '') && ($(this).val() != '-- Select Area --')) {
            alert($(this).closest('td').find($("input[name=test]")).val());
        }
    });
    return false;
});

If anyone can describe the correct jQuery to get the textbox value I would greatly appreciate it.

Thanks in advance.

Answer

Jamie Pollard picture Jamie Pollard · Feb 26, 2014

Access it by id?

$("#test").val();

The # in this example means find an element by its id (jQuery docs)