Results 1 to 3 of 3

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

Hybrid View

  1. #1
    Join Date
    Dec 2008

    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?


  2. #2
    Join Date
    Feb 2013
    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:
    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.
    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:
    <!doctype html>

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

    <script type="text/javascript" src="js/jquery.js"></script>
    <script type='text/javascript'>

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

    });// End Jquery

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

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

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