简体   繁体   中英

Jquery - Getting a parent element's data-id

been looking through previously asked questions but can't find much help.

I have the following html code that sends through a data-id to the following modal, when the user submits the form i have created a ('#edit-form').submit function which needs to send through the previously mentioned data-id.

Here's my code

Button to Open Modal >>

<button type="button" class="edit-group" title="Edit Group" data-id="<?php echo $group->id ?>" data-name="<?php echo $group->groupName ?>">Edit Group</button>

Form inside modal:

<form class="form-horizontal" id="edit-template-form">
    <div class="modal-body">
        <div class="form-group">
            <label for="edit-group-name" class="col-sm-2 control-label">Group name</label>
        <div class="col-sm-10">
            <input type="text" name="groupName" class="form-control" id="edit-template-name" placeholder="New Group Name">
        </div>
    </div>
    <input type="hidden" id="edit-template-id">
    </div>
    <div class="modal-footer">
        <button type="button" class="md-close" data-dismiss="modal">Cancel</button>
        <button type="submit" class="btn btn-primary btn-flat">Save Changes</button>
    </div>
</form>

Jquery

$('#edit-template-form').submit(function (e) {
    e.preventDefault();
    var data = {
        id: $(this).parent().val($(this).data('id')),
        name: $('#edit-template-name').val()
    };
    console.log(data);
    return false;
});

this keyword refers to data object itself not #edit-template-form . So store the variable this before using it like below:

$('#edit-template-form').submit(function (e) {
    e.preventDefault();
    var form = $(this);
    var data = {
        id: form.parent().val(form.data('id')),
        name: $('#edit-template-name').val()
    };
    console.log(data);
    return false;
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM