pass the form name to jQuery

0

I have the following function that sends a form:

function enviar_formulario() {
    document.search.submit();
}

When I want to call the function I do this:

        <select name='busca' onChange='enviar_formulario(search)'>
            <option value="1">ID</option>
            <option value="2">NOME</option> 
        </select>   

And whenever I select the option it sends the form.

Well it works, but form has to be named search . How do I pass the form name to be sent to the function?

Example:

enviar_formulario(nome_do_formulário_a_ser_enviado)
    
asked by anonymous 17.11.2016 / 13:52

3 answers

2

With jQuery you check out getting the submit event of any form and then get it name it:

HTML:

<form name="form1" action="">
  <input type="text" value="Olá">
  <input type="submit" value="Go">
</form>

Javascript:

$("form").submit(function( event ) { 
  event.preventDefault();
  var nome = $(this).attr("name");
  alert(nome);
});

JSFiddle : link

Edited:

With select you can do this:

<select name='busca' onChange="enviar_formulario('form1')">
     <option value="1">ID</option>
     <option value="2">NOME</option> 
</select>

Javascript:

function enviar_formulario(nome){
    $("form[name='"+ nome + "']").submit();
}
    
17.11.2016 / 14:02
3

If you used as I suggested in the other answer apply well here too:

$('select[name="busca"]').on('change', enviar_formulario);

function enviar_formulario() {
    document[this.name].submit();
}

Or simply go look for form where this select is by DOM hierarchy:

$('select[name="busca"]').on('change', function() {
    $(this).closest('form').submit();
}
    
17.11.2016 / 14:37
0

Try to do the function like this:

function enviar_formulario(nome) {
  document[nome].submit();
}

UPDATE

I thought it would work that way so it did not change much of what you already used.

Try it like this:

document.querySelector('select[name=busca]').addEventListener('change', function() {
  enviarFormulario('form'+this.value);
});

function enviarFormulario(nome) {
  form = document.querySelector('form[name='+nome+']');
  if(form) {
    form.submit();
  }
}
    
17.11.2016 / 13:54