Search code examples
jqueryshow-hidejquery-events

How to hide parent element by clicking on child button in jQuery


I have following HTML code and I want to hide div with class editfield and editfieldlink link and show div with class value. I tried following jQuery code it did not work for me, but this works fine if I hide a parent like this statement: $(this).closest('div.editfield').parent().hide();

<tr class="row-fluid settingsrow">
                <td class="span2">
                    <strong>Name</strong>
                </td>
                
                <td class="span8">
                <div class="value">ALI ASAD</div>
                <div class="editfield">
                    <form class="form-vertical">         
                        <div class="control-group">
                            <label class="control-label">First Name</label>
                            <div class="controls">
                                <input type="text" name="firstname" id="firstname" placeholder="Ali">
                            </div>
                        </div>
                        
                        <div class="control-group">
                            <label class="control-label">Last Name</label>
                            <div class="controls">
                                <input type="text" name="lastname" placeholder="Asad">
                            </div>
                        </div>
                        <div class="control-group">
                            <div class="controls">
                                <button type="submit" class="btn btn-primary btn-mini">Save Changes</button>
                                <button class="btn btn-inverse btn-mini cancelactionsettings">Cancel</button>
                            </div>
                        </div>
                    </form> 
                </div>
                </td>
                <td class="span1"><a href="#" class="editfieldlink" style="text-decoration:none"><small>Edit</small></a></td>
            </tr>

And my JavaScript is like this:

$(document).ready(function(e) 
    {
    $('#settingseditor .cancelactionsettings').click(function(event)
    {
        event.preventDefault();

        $(this).closest('div.editfield').hide();
        $(this).closest('div.value').show();
        $(this).closest('a.editfieldlink').hide();
        
    });
    
});

Solution

  • You just aren't traversing correctly

    $(document).ready(function (e) {
        $('#settingseditor .cancelactionsettings').click(function (event) {
            event.preventDefault();
            $(this).closest('div.editfield').hide();
            $(this).closest('div.editfield').prev('.value').show(); // .value is a prev sibling of div.editfield
            $(this).closest('td').next().find('a.editfieldlink').hide();// anchor is in the next sibling td
        });
    });
    

    fiddle