Hi, How do I copy the selected value of a drop down list to a hidden field with js?
thanks.
Printable View
Hi, How do I copy the selected value of a drop down list to a hidden field with js?
thanks.
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:
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:var foo = document.getElementById('foo');
var bar = document.getElementById('bar');
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/Code:if (document.addEventListener !== undefined) {
foo.addEventListener('change', function () {
bar.value = this.options[this.selectedIndex].value;
}, true);
The JavaScript goes in the bottom of the html, like so:
Code:<!doctype html>
<html>
<head>..</head>
<body>
<div><span>...
<script>..</script>
</body>
</html>
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>