Javascript 在更改之前获取选择(下拉)的值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4076770/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Getting value of select (dropdown) before change
提问by Alpesh
The thing I want to achieve is whenever the <select>
dropdown is changed I want the value of the dropdown before change. I am using 1.3.2 version of jQuery and using on change event but the value I am getting over there is after change.
我想要实现的事情是每当<select>
下拉列表更改时,我想要更改之前下拉列表的值。我正在使用 1.3.2 版本的 jQuery 并在更改事件上使用,但我在那里得到的值是在更改之后。
<select name="test">
<option value="stack">Stack</option>
<option value="overflow">Overflow</option>
<option value="my">My</option>
<option value="question">Question</option>
</select>
Lets say currently option My is selected now when I change it to stack in the onchange event (i.e. when I changed it to stack) I want it's previous value i.e. my expected in this case.
假设当前选项 My 现在被选中,当我在 onchange 事件中将其更改为堆栈时(即,当我将其更改为堆栈时)我希望它是以前的值,即我在这种情况下的预期值。
How can this be achieved?
如何做到这一点?
Edit:In my case I am having multiple select boxes in the same page and want same thing to be applied to all of them. Also all of my select are inserted after page load through ajax.
编辑:就我而言,我在同一页面中有多个选择框,并希望将相同的内容应用于所有选择框。此外,我的所有选择都是在通过 ajax 加载页面后插入的。
回答by Andy E
Combine the focusevent with the changeevent to achieve what you want:
将焦点事件与更改事件结合起来以实现您想要的:
(function () {
var previous;
$("select").on('focus', function () {
// Store the current value on focus and on change
previous = this.value;
}).change(function() {
// Do something with the previous value after the change
alert(previous);
// Make sure the previous value is updated
previous = this.value;
});
})();
Working example: http://jsfiddle.net/x5PKf/766
工作示例:http: //jsfiddle.net/x5PKf/766
回答by Avi Pinto
please don't use a global var for this - store the prev value at the data here is an example: http://jsbin.com/uqupu3/2/edit
请不要为此使用全局变量 - 将 prev 值存储在数据中,这是一个示例:http: //jsbin.com/uqupu3/2/edit
the code for ref:
参考代码:
$(document).ready(function(){
var sel = $("#sel");
sel.data("prev",sel.val());
sel.change(function(data){
var jqThis = $(this);
alert(jqThis.data("prev"));
jqThis.data("prev",jqThis.val());
});
});
just saw that you have many selects on page - this approach will also work for you since for each select you will store the prev value on the data of the select
刚刚看到您在页面上有很多选择 - 这种方法也适用于您,因为对于每个选择,您都会将 prev 值存储在选择的数据上
回答by user1310312
I go for Avi Pinto's solution which uses jquery.data()
我选择使用 Avi Pinto 的解决方案 jquery.data()
Using focus isn't a valid solution. It works at first time you change the options, but if you stay on that select element, and press key "up" or "down". It won't go through the focus event again.
使用焦点不是有效的解决方案。它在您第一次更改选项时起作用,但是如果您停留在该选择元素上,然后按“向上”或“向下”键。它不会再次通过焦点事件。
So the solution should be more looks like the following,
所以解决方案应该更像下面这样,
//set the pre data, usually needed after you initialize the select element
$('mySelect').data('pre', $(this).val());
$('mySelect').change(function(e){
var before_change = $(this).data('pre');//get the pre data
//Do your work here
$(this).data('pre', $(this).val());//update the pre data
})
回答by August Lilleaas
Track the value by hand.
手动跟踪值。
var selects = jQuery("select.track_me");
selects.each(function (i, element) {
var select = jQuery(element);
var previousValue = select.val();
select.bind("change", function () {
var currentValue = select.val();
// Use currentValue and previousValue
// ...
previousValue = currentValue;
});
});
回答by free4ride
$("#dropdownId").on('focus', function () {
var ddl = $(this);
ddl.data('previous', ddl.val());
}).on('change', function () {
var ddl = $(this);
var previous = ddl.data('previous');
ddl.data('previous', ddl.val());
});
回答by Cica Gustiani
I am using event "live", my solution is basically similiar with Dimitiar, but instead of using "focus", my previous value is stored when "click" is triggered.
我正在使用事件“live”,我的解决方案基本上与 Dimitiar 类似,但不是使用“focus”,而是在触发“click”时存储我以前的值。
var previous = "initial prev value";
$("select").live('click', function () {
//update previous value
previous = $(this).val();
}).change(function() {
alert(previous); //I have previous value
});
回答by Deshani Tharaka
keep the currently selected drop down value with chosen jquery in a global variable before writing the drop down 'on change' action function. If you want to set previous value in the function you can use the global variable.
在编写下拉“更改时”操作函数之前,将当前选定的下拉值与选定的 jquery 保存在全局变量中。如果要在函数中设置以前的值,可以使用全局变量。
//global variable
var previousValue=$("#dropDownList").val();
$("#dropDownList").change(function () {
BootstrapDialog.confirm(' Are you sure you want to continue?',
function (result) {
if (result) {
return true;
} else {
$("#dropDownList").val(previousValue).trigger('chosen:updated');
return false;
}
});
});
回答by JBW
I know this is an old thread, but thought I may add on a little extra. In my case I was wanting to pass on the text, val and some other data attr. In this case its better to store the whole option as a prev value rather than just the val.
我知道这是一个旧线程,但我想我可以补充一点。就我而言,我想传递文本、val 和其他一些数据属性。在这种情况下,最好将整个选项存储为 prev 值,而不仅仅是 val。
Example code below:
示例代码如下:
var $sel = $('your select');
$sel.data("prevSel", $sel.clone());
$sel.on('change', function () {
//grab previous select
var prevSel = $(this).data("prevSel");
//do what you want with the previous select
var prevVal = prevSel.val();
var prevText = prevSel.text();
alert("option value - " + prevVal + " option text - " + prevText)
//reset prev val
$(this).data("prevSel", $(this).clone());
});
EDIT:
编辑:
I forgot to add .clone() onto the element. in not doing so when you try to pull back the values you end up pulling in the new copy of the select rather than the previous. Using the clone() method stores a copy of the select instead of an instance of it.
我忘了将 .clone() 添加到元素上。当您尝试拉回最终拉入选择的新副本而不是前一个的值时,不要这样做。使用 clone() 方法存储选择的副本而不是它的实例。
回答by Nick M
How about using a custom jQuery event with an angular watch type interface;
如何使用带有角度手表类型界面的自定义 jQuery 事件;
// adds a custom jQuery event which gives the previous and current values of an input on change
(function ($) {
// new event type tl_change
jQuery.event.special.tl_change = {
add: function (handleObj) {
// use mousedown and touchstart so that if you stay focused on the
// element and keep changing it, it continues to update the prev val
$(this)
.on('mousedown.tl_change touchstart.tl_change', handleObj.selector, focusHandler)
.on('change.tl_change', handleObj.selector, function (e) {
// use an anonymous funciton here so we have access to the
// original handle object to call the handler with our args
var $el = $(this);
// call our handle function, passing in the event, the previous and current vals
// override the change event name to our name
e.type = "tl_change";
handleObj.handler.apply($el, [e, $el.data('tl-previous-val'), $el.val()]);
});
},
remove: function (handleObj) {
$(this)
.off('mousedown.tl_change touchstart.tl_change', handleObj.selector, focusHandler)
.off('change.tl_change', handleObj.selector)
.removeData('tl-previous-val');
}
};
// on focus lets set the previous value of the element to a data attr
function focusHandler(e) {
var $el = $(this);
$el.data('tl-previous-val', $el.val());
}
})(jQuery);
// usage
$('.some-element').on('tl_change', '.delegate-maybe', function (e, prev, current) {
console.log(e); // regular event object
console.log(prev); // previous value of input (before change)
console.log(current); // current value of input (after change)
console.log(this); // element
});
回答by thisisboris
I'd like to contribute another option to solve this issue; since the solutions proposed above did not solve my scenario.
我想贡献另一个选项来解决这个问题;因为上面提出的解决方案没有解决我的情况。
(function()
{
// Initialize the previous-attribute
var selects = $('select');
selects.data('previous', selects.val());
// Listen on the body for changes to selects
$('body').on('change', 'select',
function()
{
$(this).data('previous', $(this).val());
}
);
}
)();
This does use jQuery so that def. is a dependency here, but this can be adapted to work in pure javascript. (Add a listener to the body, check if the original target was a select, execute function, ...).
这确实使用了 jQuery,因此 def. 是这里的一个依赖项,但这可以适用于纯 javascript。(向主体添加一个侦听器,检查原始目标是否是选择、执行函数,...)。
By attaching the change listener to the body, you can pretty much be sure this will fire afterspecific listeners for the selects, otherwise the value of 'data-previous' will be overwritten before you can even read it.
通过将更改侦听器附加到正文,您几乎可以确定这将在选择的特定侦听器之后触发,否则 'data-previous' 的值将在您读取它之前被覆盖。
This is of course assuming that you prefer to use separate listeners for your set-previous and check-value. It fits right in with the single-responsibility pattern.
这当然是假设您更喜欢为 set-previous 和 check-value 使用单独的侦听器。它非常适合单一职责模式。
Note:This adds this 'previous' functionality to allselects, so be sure to fine-tune the selectors if needed.
注意:这会将此“先前”功能添加到所有选择中,因此请确保在需要时微调选择器。