Javascript在下拉更改时设置隐藏的表单值 [英] Javascript to set hidden form value on drop down change
问题描述
javascript新手,但我确信这很容易。不幸的是,大多数谷歌搜索结果都没有帮助。
New to javascript, but I'm sure this is easy. Unfortunately, most of the google results haven't been helpful.
无论如何,我想在下拉选项更改时通过javascript设置隐藏表单元素的值。
Anyway, I want to set the value of a hidden form element through javascript when a drop down selection changes.
我可以使用jQuery,如果它更容易获取或设置值。
I can use jQuery, if it makes it simpler to get or set the values.
推荐答案
如果您有这样的HTML,例如:
If you have HTML like this, for example:
<select id='myselect'>
<option value='1'>A</option>
<option value='2'>B</option>
<option value='3'>C</option>
<option value='4'>D</option>
</select>
<input type='hidden' id='myhidden' value=''>
所有你要做的就是将函数绑定到选择的更改
事件,并在那里执行您需要的操作:
All you have to do is bind a function to the change
event of the select, and do what you need there:
<script type='text/javascript'>
$(function() {
$('#myselect').change(function() {
// if changed to, for example, the last option, then
// $(this).find('option:selected').text() == D
// $(this).val() == 4
// get whatever value you want into a variable
var x = $(this).val();
// and update the hidden input's value
$('#myhidden').val(x);
});
});
</script>
考虑到所有事情,如果你要做很多jQuery编程,总是有打开文档。如果你给它一个机会,很容易找到你需要的东西。
All things considered, if you're going to be doing a lot of jQuery programming, always have the documentation open. It is very easy to find what you need there if you give it a chance.
这篇关于Javascript在下拉更改时设置隐藏的表单值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!