tags:

views:

78

answers:

2

I want to automatically populate a hidden form element with the value of what is entered in a single line text field in a form when submitted. How would this be done with jQuery? Thanks for any suggestions.

<form>
<input type="hidden" id="username" name="username" value="" />
<input type="text" id="email" name="email" value="[email protected]" />
<input type="submit" value="Submit" class="submit" />
</form>
A: 

This should do it:

$('form').submit(function() {
    $('#username').val($('#email').val());
}

I believe most (if not all) browsers will have this fire before the data is packaged up and sent. Give it a try.

Also give the form an ID and change 'form' to '#THEID'

Reference for the submit event:

http://api.jquery.com/submit/

Bob Fincheimer
Thanks for the reference. Reading up on it now :)
liquilife
Hi Bob, I was trying a similar solution, but for some reason the data isn't being submitted as expected. I'm using hidden fields, and updating them using the submit handler as you've suggested too. I expected it to just work, but I don't see the values being sent through in the POST :(
jamiebarrow
+1  A: 

I've found this method to work well across browsers:

<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"&gt;&lt;/script&gt;
<script type="text/javascript">
function submitMyForm(){
    $('#username').val($('#email').val());
    $('#myform').submit();
}
</script>
<title>Test</title>
</head>
<body>
<form id="myform" action="http://www.example.com" method="post">
<input type="hidden" id="username" name="username" value="" />
<input type="text" id="email" name="email" value="[email protected]" />
</form>
<button class="submit"  onclick="submitMyForm()">Submit</button>
</body>
</html>
Adam
This worked beautifully. Thank you so much.
liquilife
@liquilife Glad to help! If it worked then please mark this as the correct answer.
Adam
Oops, sorry. Yes, just marked it as correct.
liquilife
A slightly cleaner solution would involve moving the onclick of the submit button away from the HTML - link up this event handler in the script block, inside the document ready function: $(function(){});
jamiebarrow
i.e. give the submit an id of "mySubmitButton" and then do this in the script: $(function() { $("").click(function(event){ submitMyForm(); }); })
jamiebarrow