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

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'm currently using the jQuery statement below to assign an action and submit the form:

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

However, I do not want to use a id tag in the form, I want to check if there is an input with the tag name="_ method" , if so, the action and submit the form.

Any ideas how to do this search?

    
asked by anonymous 19.12.2016 / 03:44

3 answers

2

You can do this:

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

By steps:

  • identifies the input with name="_method"
  • looks for form where this input is in
  • change the attribute action
  • sends form
19.12.2016 / 06:46
1
var inputs = $("input[name=_method]");
if(inputs.length > 0) {
    var form = inputs.parent();
    form.attr("action", "/post/12");
    form.submit();
}
    
19.12.2016 / 04:24
1

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

I would particularly go with this template.

I hope I have 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);
};
    
19.12.2016 / 07:19