1

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;***  
       }
}
David Cain
  • 16,484
  • 14
  • 65
  • 75
BrianZ
  • 35
  • 7

1 Answers1

0

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?

Community
  • 1
  • 1
Riccardo Zorn
  • 5,590
  • 1
  • 20
  • 36
  • I was thinking of that method. But if I do that, I get a blank selection in all browsers, meaning it breaks it for Firefox now too. – BrianZ Jan 28 '14 at 22:17
  • No, you set selectedIndex _and_ text – Riccardo Zorn Jan 28 '14 at 22:22
  • Hmm, I'll just have to give it a look again. I tried removing .text and still nothing comes up. By reliable, do you mean that it will work cross-browser if I set selectedIndex only? The original code is the only way I got it to work in at least Firefox, but if you say this is a fix, I'll just have to dig in to that link more. – BrianZ Jan 28 '14 at 22:37
  • Just as I was getting it to start looking like it would work, we decided to change up the project. Thanks though. – BrianZ Jan 29 '14 at 20:22