-1

How can I submit a the value of a javascript variable along with a form submit? This is what I have so far:

var data = "abc";

$('form').submit(function(){
//add new hidden input field with value = data
});

Note: the html page will only have a single form.

James
  • 2,811
  • 3
  • 25
  • 29
  • 1
    Duplicates: http://stackoverflow.com/questions/9085091/submit-a-post-variable-with-javascript http://stackoverflow.com/questions/1350917/send-post-variable-with-javascript – Lack Jul 08 '12 at 02:54
  • Further possible duplicates: http://stackoverflow.com/questions/9084749/how-do-i-submit-a-post-variable-with-javascript http://stackoverflow.com/questions/9882211/pass-javascript-variable-to-php-post I'm somewhat new but seeing the three answers already submitted I'm inclined to ask if this is the best way to [handle obvious duplicates](http://meta.stackexchange.com/questions/10841/how-should-duplicate-questions-be-handled) – Lack Jul 08 '12 at 03:03

3 Answers3

4

Why not simply

$('form').submit(function(){
    $('<input type="hidden" name="data" />').attr('value', data).appendTo(this);
});
VoteyDisciple
  • 37,319
  • 5
  • 97
  • 97
1
$('form').submit(function(){
    $(this).append($('<input />').attr('name', 'data').attr('value', data));
});
gaurang171
  • 9,032
  • 4
  • 28
  • 30
0
var data = "abc";

$('form').submit(function(){
    $("form").append('<input type="hidden" name="data" value="' + data + '"');
});
Max Hudson
  • 9,961
  • 14
  • 57
  • 107
  • 1
    Careful concatenating `data` into the input tag; if it contains a quote mark the resulting tag will be invalid. The `.attr()` or (in this particular case) `.val()` functions will do this more reliably. – VoteyDisciple Jul 08 '12 at 02:55