Amyth
Amyth

Reputation: 32959

remove the div above

i have a template that looks something like this.

Sample Template

<div id="form-entry">
    <h4>Some heading here</h4>
    <div class="form-field">
        <label>Some Label</label>
        <input type="text" class="some_text" />
    </div>
    <div class="form-field">
        <label>Some Label</label>
        <input type="text" class="some_text" />
    </div>
    <div class="form-field">
        <label>Some Label</label>
        <input type="text" class="some_text" />
    </div>
    <div class="form-field">
        <input type="checkbox" />
        <label>Some Label</label>
    </div>
    <div class="form-field">
        <label>Some Label</label>
        <textarea></textarea>
    </div>
</div>

I want to remove (or hide) the form-field div above the div that contains checkbox input if a user checks the checkbox. The HTML is rendered automatically and do not have any specific id's or classes. How do i go about doing this. will jQuery position will be of any use?

JS

$('.form-field input[type=checkbox]').click( function(){
    entity = $(this);
    dad = entity.parent(); // This gets the form-field div element that contains the checkbox
}); 

how do i capture the form-field div element above the dad element ?

Upvotes: 0

Views: 1620

Answers (4)

Wouter de Kort
Wouter de Kort

Reputation: 39888

You can use the following jQuery:

$('.form-field input[type=checkbox]').click(function() {
    $(this).parent().prev().toggle(); // parent is the checkboxs div, prev returns the previous element in the DOM
});​

Toggle will hide/show the previous div each time the checkbox is clicked.

Here is a jsFiddle that shows how this works

Upvotes: 1

adeneo
adeneo

Reputation: 318302

$('.form-field input[type=checkbox]').on('change', function(){
    if (this.checked) 
        $(this).closest('.form-field').prev().remove();
}); 

Removes the .form_field above the .form_field that contains the checkbox, if it's checked ?

Upvotes: 7

Kevin Bowersox
Kevin Bowersox

Reputation: 94499

$('.form-field input[type=checkbox]').click( function(){
    entity = $(this);
    dad = entity.parent().prev().remove(); // This gets the form-field div element that contains the checkbox
}); 

Upvotes: 0

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382274

You could do

$('#form-entry input[type="checkbox"]').change(function(){
    $(this).parent().prev().remove();
});

Demonstration

Upvotes: 1

Related Questions