Changing the text for the selected parameter only when it is selected in the selected mode

I'm not sure if I confused everyone with the above name. My problem is as follows.

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

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

I can do it by calling

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

in the onChange event, which works fine. The problem here is when the user decides to change the selection, the search text with the changed text is displayed in the drop-down list. This should show the source list.

I'm at a dead end! is there an easier way to do this?

Any help would be great.

thank

+5
2

- reset :

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/

+3

jquery. : http://jsfiddle.net/kb7CW/1/

script:

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

});
+2

All Articles