1

I have a select box with a number of options. When a selection is made, I replace the displayed text using JQuery:

$("#dropdownlist").change(function () {
    var selected = $(this).find(":selected");
    selected.text('foo');
});

I'd then like to restore the original value when the select is dropped down. How can I do this?

I've tried using the 'click' event but this gets fired multiple times throughout the selection process, meaning that 'foo' always gets overwritten.

Thanks in advance.

Jonathan
  • 13,947
  • 17
  • 94
  • 123

2 Answers2

1

Approach 1: Just noticed that the below solution in approach 2 is not working when changed the drop down value using keyboard and tabbed out.

So in this approach I used a text box over the drop down, so you don't need to worry about changing the drop down value. DEMO

PS: I have used JQuery UI Position API

var $ddInput = $("#dropdownInput");

$ddInput.position({
  my: "left top",
  at: "left top",
  of: "#dropdownlist"
});

$("#dropdownlist").change(function (event) {
    $ddInput.val('foo');
});

Approach 2: We need an int flag as the change is calling the click again, see my code below. DEMO

var optionChanged = 0;

$("#dropdownlist").change(function (event) {
    var selected = $(this).find(":selected");
    selected.attr('data-orig', selected.val());
    selected.text('foo');
    optionChanged = 1;       
});

$("#dropdownlist").click (function () {     

    if (optionChanged == 2) {
        var selected = $(this).find(":selected");
        var tmp = selected.attr('data-orig');
        selected.attr('data-orig', selected.val());
        selected.text(tmp);      
    }
    optionChanged = 2;       
});
Selvakumar Arumugam
  • 79,297
  • 15
  • 120
  • 134
0

Try a data property like:

selected.attr('data-oldtext', selected.text());

Before you change it.

The element must be "rendered" with the attribute empty or with the original text already.

<option data-oldtext="">xxx</option>
giubueno
  • 58
  • 8
  • 2
    His problem is when to restore it, anyway, `.data('oldtext')` is better. – gdoron Feb 08 '12 at 19:39
  • Using the "mouse" events to change and restore depending if it is over or going off the select element may work. Am I right? – giubueno Feb 08 '12 at 19:48