Question

I have a drop-down with a specified value, when a user changes that value, they are warned about doing so. If they click OK, the text in the drop-down changes. If they click Cancel, the selected option reverts to the original selection. This works perfectly in Firefox, but if the user selects Cancel in Chrome and IE, the drop-down text is removed, although the value is kept. If the user clicks OK, it works in all browsers as well. Is there something IE and Chrome specific I need to do with the below marked line to make it work cross browser?

(I'm using prototype library)

JavaScript function called with onChange="typeChange(this)" in the Select tag:

function typeChange(element) {

     var oldValue = element.defaultValue;
     var newValue = element.value;
     var oldDisplayValue=jQuery('select[name="type"] option').map(function() { 
                 if (jQuery(this).attr('defaultSelected')==true) 
                      return this }).get(0).text;
     var newDisplayValue = element.options[element.selectedIndex].text

        if (window.confirm('Are you sure?)) {
        element.defaultValue = newValue;
        element.options[element.selectedIndex].text = newDisplayValue;
       } else {
        element.value = element.defaultValue;
        ***element.options[element.selectedIndex].text = oldDisplayValue;***  
       }
}
Was it helpful?

Solution

You should set selectedIndex instead, it's a more reliable way of achieving this. You need to iterate through the items to find the index of the one you're looking for, this post will help you:

JavaScript - How to set selectedIndex of select element using display text?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top