Javascript/Jquery方法获取更改事件下拉列表的上一个选定值



我有下面的php和javascript代码片段。

<td align="center">
<select id = "selectedUnit" class="form-control" onchange="saveToDatabase(this.value,'Unit','<?php echo $ingredientArray[$i][0]; ?>')"><?php 
$j=0;
for($j=0;$j<count($unitTypeArray);$j++) { ?>
<option value="<?php echo $unitTypeArray[$j][0]; ?>" <?php if($ingredientArray[$i][4] == $unitTypeArray[$j][0]){ echo 'selected';} ?>><?php echo $unitTypeArray[$j][1]; ?></option><?php 
} ?>
</select>
</td>

上面是我的下拉列表,我想要的是在下拉更改事件上获得以前选择的值,如下所示。

function saveToDatabase(editableObj,column,id) {
//editableObj gives me the currently changing value .
// How I will get the previous selected value ?I am doing it as follows.
var $selected = $(this).find(':selected');   
var text = $selected.prev().text(); //previous value
}

请帮我一下。谢谢。

第一个选项尝试这个js代码,但当u第一次更改时,将没有以前选择的值。

var previous;
function saveToDatabase(editableObj,column,id) {
alert(previous); //print previous value
var $selected = $(this).find(':selected');   
previous= $selected.text();
}

第二个选项更改此线路

<select id = "selectedUnit" class="form-control" onchange="saveToDatabase(this.value,'Unit','<?php echo $ingredientArray[$i][0]; ?>')">

到这个

<select id = "selectedUnit" class="form-control" onclick="saveToDatabase(this.value,'Unit','<?php echo $ingredientArray[$i][0]; ?>')">

js将是

function saveToDatabase(editableObj,column,id) {
var $selected = $(this).find(':selected');   
previous= $selected.text();
alert(previous);
}

您所做的是在onchangefocus事件上启动一个函数。当值更改时,它将激发。因此,您无法获取以前的值。

您应该处理的事件是onclick,它将为您提供以前的值,然后可以触发onchange以获得更改的值。如果您使用jQuery:,我建议您使用以下策略

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;
});

你可以在这里找到它:https://stackoverflow.com/a/4076949/1957479

最新更新