How to define an attribute to the parent form of a given input?

Asked

Viewed 79 times

1

I have the following form:

<form id="excluir" class="form-horizontal" role="form" method="POST">
    <input type="hidden" name="_token" value="s59zI8Ehg0dw2CVnmqpfGgyyuHKJDHSF">
    <input type="hidden" name="_method" value="DELETE">
</form>

I am currently using the jQuery statement below to assign an action and submit the form:

$('#excluir').attr('action', '/post/12');
$('#excluir').submit();

However, I don’t want to use a tag id in the form, I want to check if in the form there is an input with the tag name="_method", if yes, I will assign the action and submit the form.

Any idea how to do this search?

3 answers

2


You can do it like this:

$('input[name="_method"]').closest('form').attr('action', '/post/12').submit();

In steps:

  • identifies the input with name="_method"
  • looking for the form where this input is inside
  • changes the attribute action
  • sends the form

1

var inputs = $("input[name=_method]");
if(inputs.length > 0) {
    var form = inputs.parent();
    form.attr("action", "/post/12");
    form.submit();
}

1

You can try this solution, a little more code, but when using selectors in chain, you end up slowing the performance of the software/site. Something that helps also always use variaveia and leave the saved elements in memory once they have been used.

I would particularly go with this model.

I hope I’ve helped.

// CHANGES FORM DEFAULT BEHAVIOUR
function applyFormActions( callback ) {

    var formAction = '/post/12';

    // FIND FOR ANY ELEMENT WHICH HAS THE GIVEN ATTRIBUTE
    var hasMethod = $('[name="_method"]'); // [attrName = "value"]

    if( hasMethod.lenght ){
        // GETS ELEMENT WRAPPED FORM
        var form = hasMethod.parents('form');

        // ADD ANY ACTION TO THE FORM
        form.attr('action', formAction);

        form.on('submit', function (event) {
            // IN CASE YOU ARE USING ANY OTHER ELEMENT APART FROM A BUTTON.

            event.preventDefault();

            if( typeof callback === 'function' && callback ){
                callback();
            }

        });
    }   
}
// CALL THE FUNCTION
applyFormActions( custonActionForm );

// CALLBACK FUNCTION
custonActionForm(){
    // YOUR CUSTOM ACTION FOR THE FORM
    alert(1);
};
  • 1

    So much code... what do you need the callback for? In which case do you need the second check here typeof callback === 'function' && callback ?

  • If callback is Undefined or different from Function, it will give an error.

  • What I meant to say is that enough if( typeof callback === 'function'){ for if callback was a function the second condition of && is guaranteed, ie is redundant.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.