Wednesday, May 18, 2016

Javascript HTML - Firefox does not show default selected value on page load

Problem:
I have a web page where user will enter his/her Date of Birth by choosing from the Month, Day and Year List.
Date of Birth Drop Down List

Date of Birth will automatically be saved after clicking the Next button. Which I have verified successful.


When user clicked the back button, page should automatically select the previously entered Date of Birth. My Jquery library is jquery-1.12.3 and my jquery code is this:
 var dobth = $('#dobthOrig').val();  
 var comp = dobth.split('/');  
 var m = parseInt(comp[0], 10) - 1;  
 var d = parseInt(comp[1], 10);  
 var y = parseInt(comp[2], 10);      
 $('select.month option[value='+m+']').attr('selected','true');  
 $('select.day option[value='+d+']').attr('selected','true');  
 $('select.year option[value='+y+']').attr('selected','true');   

However, when user clicked the back button, the Date drop down displayed current date (which is the default date) and not the selected date. I checked thru Dev Tool of Firefox and correct value is selected but display is not.


Selected Day

Selected Month


Solution: 
 autocomplete="off"  
- I searched from forum that code
- But what worked perfectly for me is changing the "attr" attribute to "prop".
 $('select.month option[value='+m+']').prop('selected','selected');  
 $('select.day option[value='+d+']').prop('selected','selected');  
 $('select.year option[value='+y+']').prop('selected','selected');