简体   繁体   English

使用jQuery在选择框中获取以前选择的项目

[英]Getting previously selected item in select box with jQuery

I have a single item HTML select box on which I'd like to find out the what item was selected just prior to changing selection to the new item. 我有一个单项HTML选择框,我想在将选择更改为新项目之前找出选择的项目。

By the time the change event is fired, it's already too late: 到更改事件被触发时,已经太晚了:

$("select").change(function () {
  var str = "";
  $("select option:selected").each(function () {
      // this will get me the current selected item (the new one)
      str += $(this).text() + " "; });          
})

The docs say that 'The change event fires when a control loses the input focus and its value has been modified since gaining focus.' 文档说'当控件失去输入焦点并且自获得焦点后其值已被修改时,更改事件将触发。

However, trapping the 'blur' event doesn't seem to be the right event either and there's no "onFocusLost" type of event.. 但是,捕获'blur'事件似乎也不是正确的事件,并且没有“onFocusLost”类型的事件。

Is this feasible in a cross-browser compatible way without a lot of hoop jumping? 这是否可以跨浏览器兼容的方式,没有很多箍跳?

This should capture the value before it changes. 这应该在更改之前捕获值。 The value will be grabbed as soon as the user opens the select menu, but before they actually select something. 一旦用户打开选择菜单,但在实际选择某些内容之前,将抓取该值。

        $(document).ready(function(){
            $('select').focus(function(){
                var theValue = $(this).attr('value');
            });
    });

只是一个想法,但是你不能一旦你处理更改事件,将值设置为某个变量,所以下次处理它时,你会有这个值吗?

You could do something like this 你可以这样做

$(document).ready(function() {
    $("select").each(function(){
        var str = getSelectedText(this);
        $(this).data('selected',str);
    }).change(function () {
        var str = getSelectedText(this);
        var selectedbefore = $(this).data('selected');
        $(this).data('selected',str);
    });
});
function getSelectedText(obj){
    var str = "";
    $(obj).closest('select').find("option:selected").each(function () {
        str += $(this).text() + " ";
    });
    return str;
}

Here is an up-to date solution using .on 这是使用.on的最新解决方案

$('#form-id').on('focus','select',function(){
 var previous = $(this).children('option').filter(':selected').val();
});

However for what I wanted to achieve, the above was too loose, I needed the value that was selected on initial page output as the above will give me the incorrect value after the user changes it more than once before submitting the form data. 然而,对于我想要实现的目标,上面的内容过于宽松,我需要在初始页面输出中选择的值,因为在用户在提交表单数据之前多次更改它之后,上面将给出不正确的值。

My solution was to add a "previous" attribute to the select element populated with the value on output, then change it on a "success" result from Ajax when saved: 我的解决方案是将“previous”属性添加到用输出值填充的select元素,然后在保存时从Ajax的“success”结果中更改它:

<select name="status" id="status" previous="D"> ... </select>

Then upon the user pressing a cancel button on a confirmation popup or there being a Ajax error I just did: 然后,当用户在确认弹出窗口上按下取消按钮或者出现Ajax错误时,我刚刚做了:

$('#status').val($('#status').attr('previous')).attr('selected',true);

and if upon Ajax "success" change the "previous" attribute to the new successfully saved value: 如果在Ajax“success”上将“previous”属性更改为新成功保存的值:

$('#status').attr('previous',$('#status').children('option').filter(':selected').val());

Suitable for a single for form element but I required an adaptation where I have a list of accounts each with an account status setting select menu that triggers a jQuery UI dialogue box that in turn deciphers the Ajax Call to save the setting, A single hidden form with a set of fields is populated with values from the select menu using .on('change') 适用于单个表单元素,但我需要一个适应,我有一个帐户列表,每个帐户状态设置选择菜单触发一个jQuery UI对话框,然后解密Ajax调用以保存设置,一个隐藏的形式使用.on('change')从选择菜单填充一组字段

Here is one of the select menus (Unique ID's would normally be used but in my case there a couple of server side reasons why I can't use them this time around hence the combined use of the attributes "rel" and "type", same code saves changes to different database tables): 这是一个选择菜单(通常会使用唯一ID,但在我的情况下有几个服务器方面的原因,为什么我这次不能使用它们因此结合使用属性“rel”和“type”,相同的代码保存对不同数据库表的更改):

<select name="status" rel="23" type="company" previous="P">
    <option value="P" selected="selected">Pending</option>
    <option value="D">Deactivated</option>
    <option value="A">Activated</option>
</select>

Because there are 3 points in the script where a fail can occur and one success it made sense to make a function: 因为脚本中有3个点可以发生故障,并且一次成功就可以创建一个函数:

function set_select(saved)
    {
        var e = $(':input[type="'+$('#status-type').val()+'"][rel="'+$('#status-id').val()+'"]');
        if(saved) e.attr('previous',e.children('option').filter(':selected').val());
        e.val( e.attr('previous') ).attr('selected',true);  
    };

Here is the jQuery UI Dialog code: 这是jQuery UI Dialog代码:

    $('#update-confirm').dialog({
        autoOpen:false,
        resizable:false,
        height:230,
        modal:true,
        buttons:{
            "Change": function(){
                var exec = false;
                $dialog = $(this);
                switch($('#status-type').val())
                {
                    default: set_select(false); break;
                    case 'company': exec = 'save-company-status'; break;
                    case 'user': exec = 'save-user-status'; break;
                };
                if(exec)
                {
                    $.ajax({
                        type: 'POST',
                        url: '/sys.manager/apps.manager.php?do='+exec,
                        data: $('#form-status').serialize(),
                        success: function(response)
                        {
                            if(!response.result || response.result == 'false')
                            { 
                                console.log('Fail');
                                set_select(false);
                            } else {
                                console.log(response.result);
                                console.log(response.mail);
                                $dialog.dialog('close');
                                set_select(true);
                            }

                        },
                        error: function(response) {
                            set_select(false);
                        }
                    });
                };
            },
            Cancel: function() {
                set_select(false);
                $(this).dialog('close');
            }
        }
    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM