在文档准备就绪和变更上获得选择价值

时间:2014-06-08 05:36:09

标签: jquery

我试图在页面加载和更改时获取下拉选择元素(在表单内)的值,并将其传递给另一个输入(隐藏)。这是我到目前为止尝试过的代码。

这个适用于页面加载,但现在在更改后工作:

        jQuery( document ).ready(function() {
        var comment_post_ID = jQuery("#alldentists").val();
            jQuery("#comment_post_ID").val( comment_post_ID );
        });

这不适用于页面加载,但正在处理更改选择选项。

        jQuery( document ).ready(function() {

            jQuery( "#alldentists" ).change(function() {
                var comment_post_ID = jQuery("#alldentists").val();

            });
            jQuery("#comment_post_ID").val( comment_post_ID );
        });

有什么方法可以获得页面加载和更改的价值?我正在使用jQuery 1.11.0。

1 个答案:

答案 0 :(得分:1)

全局声明变量“comment_post_ID”

  <select name="alldentists" id="alldentists"><option>One</option>
    <option>Two</option>
        <option>Three</option>
    </select>
    <input type="text" id="comment_post_ID"/> 

jQuery(document).ready(function() {
      var comment_post_ID=jQuery("#alldentists").val();
      jQuery("#alldentists").on('change', function(e) {
        comment_post_ID = jQuery("#alldentists").val();
        jQuery("#comment_post_ID").val(comment_post_ID);  
      });
      jQuery("#comment_post_ID").val(comment_post_ID);
});

演示:

http://jsfiddle.net/3PPvH/1/

相关问题