Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select the outer <div> around the <input /> field?

I'm doing my first steps with jQuery and need help to choose an appropriate selector for my problem. I have the following HTML in a Django template:

{% for field in form %}

    <div class="control-group">

        <label class="control-label" for="{{ field.label }}">{{ field.label }}</label>

        <div class="controls">

            {% if field.html_name == "field_1" %}

                <input class="input-xlarge" id="{{ field.label }}" type="text" name="{{ field.html_name }}" />

            {% elif field.html_name == "field_2" %}

                <input class="input-mini" id="{{ field.label }}" type="text" name="{{ field.html_name }}" />

            {% endif %}

        </div>

    </div>

{% endfor %}

I need to do something with the <input /> fields for which I have the following selectors:

var $inputField1 = $('input[name="field_1"]');
var $inputField2 = $('input[name="field_2"]');

My problem now is that I need to be able to select a <div class="control-group"></div> for a particular <input /> field in order to change the class of this <div>. How do I do that? Do I need the parent selector for that? I'm a bit confused. Please help. Thank you very much!

like image 958
pemistahl Avatar asked Nov 22 '12 12:11

pemistahl


1 Answers

You can't do it with just a selector. You will need to select the input element as you currently do, and then use the .closest() method to get the ancestor div:

var controlGroup = $('input[name="field_1"]').closest('.control-group');
like image 93
James Allardice Avatar answered Nov 14 '22 23:11

James Allardice