-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.

2

3 Answers 3

4

Why not simply

$('form').submit(function(){
    $('<input type="hidden" name="data" />').attr('value', data).appendTo(this);
});
Sign up to request clarification or add additional context in comments.

Comments

1
$('form').submit(function(){
    $(this).append($('<input />').attr('name', 'data').attr('value', data));
});

Comments

0
var data = "abc";

$('form').submit(function(){
    $("form").append('<input type="hidden" name="data" value="' + data + '"');
});

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.