Populate hidden form element value with the value of a text field on form submit (jQuery)

前端 未结 2 1420
谎友^
谎友^ 2021-01-15 09:42

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 jQ

相关标签:
2条回答
  • 2021-01-15 10:21

    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/

    0 讨论(0)
  • 2021-01-15 10:24

    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"></script>
    <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="some.email@typed.here.on.webpage.com" />
    </form>
    <button class="submit"  onclick="submitMyForm()">Submit</button>
    </body>
    </html>
    
    0 讨论(0)
提交回复
热议问题