1

I have following php with javascript code snippet.

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

Above is my dropdown , what I want is to get the previous selected value on dropdown change event , like below.

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
}

Please help me on this .Thanks.

user2656780
  • 37
  • 1
  • 9

2 Answers2

1

first option try this js code, but when u will change first time then there will be no previous selected value.

 var previous;

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

second option change this line

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

to this

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

and js for this will be

function saveToDatabase(editableObj,column,id) {
       var $selected = $(this).find(':selected');   
       previous= $selected.text();
       alert(previous);
    }
Imran Qamer
  • 2,067
  • 2
  • 22
  • 45
1

What you were doing is firing a function on onchange or focus event. It fires when the value is changed. So you can't get previous value.

The event you should work is onclick that will give you the previous value and then onchange can be fired to get changed value. I suggest below strategy if you are using 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;
    });

You can find it here : https://stackoverflow.com/a/4076949/1957479

Community
  • 1
  • 1
open and free
  • 2,097
  • 18
  • 22