Javascript在下拉更改时设置隐藏的表单值 [英] Javascript to set hidden form value on drop down change

查看:153
本文介绍了Javascript在下拉更改时设置隐藏的表单值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆