Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

changing text for a selected option only when its in selected mode

I am not sure if I confused everyone with the above title. My problem is as follows.

I am using standard javascript (no jQuery) and HTML for my code. The requirement is that for the <select>...</select> menu, I have a dynamic list of varying length.

Now if the length of the option[selectedIndex].text > 43 characters, I want to change the option[selectecIndex] to a new text.

I am able to do this by calling

this.options[this.selectedIndex].text = "changed text"; 

in the onChange event which works fine. The issue here is once the user decides to change the selection, the dropdownlist is showing the pervious-selected-text with changed text. This needs to show the original list.

I am stumped! is there a simpler way to do this?

Any help would be great.

Thanks

like image 215
curioussam Avatar asked Feb 26 '13 21:02

curioussam


2 Answers

You can store previous text value in some data attribute and use it to reset text back when necessary:

document.getElementById('test').onchange = function() {

    var option = this.options[this.selectedIndex];

    option.setAttribute('data-text', option.text);
    option.text = "changed text";

    // Reset texts for all other options but current
    for (var i = this.options.length; i--; ) {
        if (i == this.selectedIndex) continue;
        var text = this.options[i].getAttribute('data-text');
        if (text) this.options[i].text = text;
    }
};

http://jsfiddle.net/kb7CW/

like image 122
dfsq Avatar answered Oct 22 '22 21:10

dfsq


You can do it pretty simply with jquery. Here is a working fiddle: http://jsfiddle.net/kb7CW/1/

Here is the script for it also:

      //check if the changed text option exists, if so, hide it
$("select").on('click', function(){
   if($('option#changed').length > 0)
   {
        $("#changed").hide()
   }
});
//bind on change
$("select").on('change', function(){
    var val = $(":selected").val(); //get the value of the selected item
    var text = $(':selected').html(); //get the text inside the option tag
    $(":selected").removeAttr('selected'); //remove the selected item from the selectedIndex
    if($("#changed").length <1) //if the changed option doesn't exist, create a new option with the text you want it to have (perhaps substring 43 would be right
          $(this).append('<option id="changed" value =' + val + ' selected="selected">Changed Text</option>');
    else
        $('#changed').val(val) //if it already exists, change its value

   $(this).prop('selectedIndex', $("#changed").prop('index')); //set the changed text option to selected;

});
like image 38
Mike Avatar answered Oct 22 '22 21:10

Mike