www.webdeveloper.com
Results 1 to 3 of 3

Thread: Copy value from drop down selection to hidden text field

  1. #1
    Join Date
    Dec 2008
    Posts
    132

    Copy value from drop down selection to hidden text field

    Hi, How do I copy the selected value of a drop down list to a hidden field with js?

    thanks.

  2. #2
    Join Date
    Feb 2013
    Posts
    46
    You use the DOM.

    Give the select menu an id.. like, <select id="foo">
    Give the hidden element an id.. like, <input type="hidden" id="bar">

    Then use the DOM to bind events to them- like this:
    Code:
    var foo = document.getElementById('foo');
    var bar = document.getElementById('bar');
    Than attach an event handler to the foo element, so that when it is changed, the selected option is set to the hidden input element's value.
    Code:
    if (document.addEventListener !== undefined) {
    foo.addEventListener('change', function () {
        bar.value = this.options[this.selectedIndex].value;
    }, true);
    Like this, http://jsfiddle.net/nMHKq/ except that only works in standards-compliant browsers- and also is bad practice because the vars are in global scope. So this is the better way: http://jsfiddle.net/nMHKq/1/

    The JavaScript goes in the bottom of the html, like so:
    Code:
    <!doctype html>
    <html>
    <head>..</head>
    <body>
      <div><span>...
      <script>..</script>
    </body>
    </html>

  3. #3
    Join Date
    Feb 2013
    Location
    New York
    Posts
    6
    You can do it easily with JQuery.

    <!DOCTYPE>
    <html>
    <head>
    <script type="text/javascript" src="js/jquery.js"></script>
    <script type='text/javascript'>
    $(document).ready(function(){

    $("select").change(function(){
    $("input[type=hidden]").val($("select option:selected").val());
    });

    });// End Jquery
    </script>

    </head>
    <body>
    <select>
    <option value="blue">Blue</option>
    <option value="red">Red</option>
    <option value="black">Black</option>
    </select>

    <input type="hidden" value="" />
    </body>
    </html>

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles