【问题标题】:Javascript/Jquery method to get previous selected value of a dropdown on change event [duplicate]Javascript / Jquery方法获取更改事件下拉列表的先前选择值[重复]
【发布时间】:2023-03-24 23:14:01
【问题描述】:

我用 javascript 代码 sn-p 跟踪 php。

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

请帮助我。谢谢。

【问题讨论】:

  • 使用变量,只要有变化就会保持以前的值..
  • @ImranQamer onchange 将如何解决这个问题,你能不能给我一个后写代码?

标签: javascript php jquery


【解决方案1】:

您所做的是在 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

【讨论】:

    【解决方案2】:

    第一个选项试试这个js代码,但是当你第一次改变时,就没有以前选择的值了。

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

    【讨论】:

    • 谢谢! ,你真的节省了我一个小时的时间。
    • 欢迎您,为将来访问的用户单击勾号,始终接受正确答案
    猜你喜欢
    • 2014-12-11
    • 1970-01-01
    • 2011-05-03
    • 1970-01-01
    • 2012-07-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-15
    相关资源
    最近更新 更多