Reputation: 9584
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!
Upvotes: 5
Views: 3078
Reputation: 564
Look into jQuery .closest():
http://api.jquery.com/closest/
... If you want a more specific answer, tell us what you want to do with your inputs :)
Upvotes: 2
Reputation: 74420
You can use .closest():
var $inputField1 = $('input[name="field_1"]');
var $targetDiv = $inputField1.closest('.control-group');
Or use parents():
var $inputField1 = $('input[name="field_1"]');
var $targetDiv = $inputField1.parents('.control-group:eq(0)');
.closest() is better as it doesn't iterate through all the DOM
Upvotes: 3
Reputation: 7663
you can use
$('input[name="field_1"]').parents('.control-group:first')
Upvotes: 0
Reputation: 165971
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');
Upvotes: 8