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!
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');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With