Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
273 views
in Technique[技术] by (71.8m points)

javascript - 在更改之前获取select(下拉列表)的值(Getting value of select (dropdown) before change)

The thing I want to achieve is whenever the <select> dropdown is changed I want the value of the dropdown before change.

(我想要实现的是每当<select>下拉列表被更改时我想要更改之前的下拉列表的值。)

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.

(我正在使用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 (ie when I changed it to stack) I want it's previous value ie 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加载页面后插入的。)

  ask by Alpesh translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Combine the focus event with the change event 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)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...