Come aggiungere ulteriori campi al modulo prima dell'invio?


111

C'è un modo per utilizzare javascript e JQuery per aggiungere alcuni campi aggiuntivi da inviare da un modulo HTTP utilizzando POST?

Intendo:

<form action="somewhere" method="POST" id="form">
  <input type="submit" name="submit" value="Send" />
</form>

<script type="text/javascript">
  $("#form").submit( function(eventObj) {
    // I want to add a field "field" with value "value" here
    // to the POST data

    return true;
  });
</script>

Risposte:


161

Sì, puoi provare con alcuni parametri nascosti.

  $("#form").submit( function(eventObj) {
      $("<input />").attr("type", "hidden")
          .attr("name", "something")
          .attr("value", "something")
          .appendTo("#form");
      return true;
  });

30
.appendTo(this)probabilmente sarebbe meglio.
— jcuenod

4
@jcuenod original appendTo('#form')è molto meglio, perché tale approccio consente di inviare un altro modulo con valori da questo.
— Andremoniy

7
Dovrai aggiungere un po 'di logica in più per evitare di accumulare questi input con ogni invio.
— amos

Probabilmente vorrai rimuovere l'elemento di input prima di aggiungerlo nel caso in cui esista già$(this).find("input[name="+"something"+"]").remove();
— K Vij

42

Prova questo:

$('#form').submit(function(eventObj) {
    $(this).append('<input type="hidden" name="field_name" value="value" /> ');
    return true;
});

Devo aggiungere dinamicamente un campo file. Ho provato ad avere type = file e il valore anche come file (sto usando WebKitDirectory, quindi in realtà ottengo gli oggetti file), tuttavia non sembra mai passarlo. Tuttavia, il testo di input viene sempre passato. Per favore aiutatemi!
— Swaathi Kakarla

La mia risposta preferita a causa dell'utilizzo thisinvece del ridondante#form
— rinogo

15
$('#form').append('<input type="text" value="'+yourValue+'" />');

10

Puoi aggiungere un hidden inputcon qualsiasi valore devi inviare:

$('#form').submit(function(eventObj) {
    $(this).append('<input type="hidden" name="someName" value="someValue">');
    return true;
});

5

Funziona:

var form = $(this).closest('form');

form = form.serializeArray();

form = form.concat([
    {name: "customer_id", value: window.username},
    {name: "post_action", value: "Update Information"}
]);

$.post('/change-user-details', form, function(d) {
    if (d.error) {
        alert("There was a problem updating your user details")
    } 
});

Sì, ma non esiste un reindirizzamento alla pagina dei risultati.
— omikron

3
dovrebbe funzionare: $('body').append(form); $(form).submit();
— Jeff Lowery,

Questo è stato il più utile per me, perché ho un gran numero di campi generati e non voglio creare campi nascosti per ciascuno.
— Sprachprofi

Perché non @Sprachprofi?
— Displee

3

Può essere utile per alcuni:

(una funzione che ti permette di aggiungere i dati al form usando un oggetto, con override per gli input esistenti, se c'è) [js puro]

(il modulo è un dominio e non un oggetto jquery [ jqryobj.get (0) se necessario ])

function addDataToForm(form, data) {
    if(typeof form === 'string') {
        if(form[0] === '#') form = form.slice(1);
        form = document.getElementById(form);
    }

    var keys = Object.keys(data);
    var name;
    var value;
    var input;

    for (var i = 0; i < keys.length; i++) {
        name = keys[i];
        // removing the inputs with the name if already exists [overide]
        // console.log(form);
        Array.prototype.forEach.call(form.elements, function (inpt) {
             if(inpt.name === name) {
                 inpt.parentNode.removeChild(inpt);
             }
        });

        value = data[name];
        input = document.createElement('input');
        input.setAttribute('name', name);
        input.setAttribute('value', value);
        input.setAttribute('type', 'hidden');

        form.appendChild(input);
    }

    return form;
}

Uso :

addDataToForm(form, {
    'uri': window.location.href,
     'kpi_val': 150,
     //...
});

puoi usarlo anche tu

var form = addDataToForm('myFormId', {
    'uri': window.location.href,
     'kpi_val': 150,
     //...
});

puoi aggiungere # se vuoi anche tu ("#myformid").

Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.