MChan
MChan

Reputation: 7162

JQuery selecting child of parent element

I am trying to return the content of a text filed as shown from the code and HTML below upon the click of the submit button, but for some reason result always returns undefined, can someone please help me by telling me what I am doing wrong /missing here and how to get the value of the text field? Thanks

<div class="col_full">       
    <div class="col_full">
        <label for="textFieldLabel">Label<small>*</small></label>
        <input type="text" id="textFieldLabel" name="textFieldLabel" value="" class="sm-form-control required">
    </div>
</div>

<div class="col_full">
    <button class="button button-3d nomargin" type="submit" id="addNewField" name="addNewField" value="submit">Add</button>
</div>

Code I tried so far:

$('#addNewField').closest('.col_full').children('[name=textFieldLabel]').val();
$('#addNewField').parent().children('[name=textFieldLabel]').val();

Upvotes: 0

Views: 74

Answers (3)

Timur Osadchiy
Timur Osadchiy

Reputation: 6209

Your input field has id. So you can just use $("#textFieldLabel").val(). If there is only one input on the page with the name textFieldLabel, you can find the input by its name as well: $("input[name=textFieldLabel]").val().

Upvotes: 4

Brijesh Bhatt
Brijesh Bhatt

Reputation: 3830

Try this

$('#addNewField').parent().prev('.col_full').find('input[name=textFieldLabel]').val();

Upvotes: 2

Milind Anantwar
Milind Anantwar

Reputation: 82231

You need to traverse to previous sibling of submit buttons parent div and then find the element in it:

$('#addNewField').parent().prev().find('[name=textFieldLabel]').val();

Working Demo

Upvotes: 3

Related Questions