Javascript remember combobox value
I currently have 3 combo boxes containing values which apply styles to the page using javascript.
All these styles are applied to a cookie and read on body load, however I'd like to also set the combo box's values to match the applied styles.
How do I go about setting a combo box value based on a cookie or applied style?
<select name="sizes" onchange="fontSi开发者_运维知识库ze(accessibility.sizes.value);">
<option value='-1'>Select</option>
<option value='10'>Small</option> <option value='12.75'>Medium</option>
<option value='15.5'>Large</option>
</select>
function fontSize(textSize) {
var element = document.getElementById('content');
if (element) {
element.style.fontSize = textSize + 'px';
createCookie("Font Size", textSize, 365);
}
}
Thanks in advance!
If changing the select is changing the style, first select the relevant value then trigger the onchange. Notice I changed your script to save the selectedIndex and to apply the change after I set the index. Also please notice I pass (this) which the the select object itself and I have added an ID to it. Lastly I put the medium fontsize as the first item in case people want to reset. Please change that to whatever is the default font size
window.onload=function() {
var sel = document.getElementById('sizes');// get the select with ID=sizes
// the following statement gets the select and sets the index to the cookie content if
// there IS a cookie, else it sets it to 0
var idx = getCookie("FontSizeIdx") || 0;
sel.selectedIndex = parseInt(idx,10); // make sure it is a number
// now call the function and pass the select to it
fontSize(sel);
}
function fontSize(sel) { // select object is passed as (this) and ends up here as (sel)
var textSize = sel.options[sel.selectedIndex].value; // get the value
var element = document.getElementById('content'); // get the content object
if(element) { // does it exist?
element.style.fontSize = textSize + 'px'; // set the font size
createCookie("FontSizeIdx", sel.selectedIndex, 365); // save the index
}
}
<select name="sizes" id="sizes" onchange="fontSize(this);">
<option value='12.75'>Select (default is medium)</option>
<option value='10'>Small</option>
<option value='12.75'>Medium</option>
<option value='15.5'>Large</option>
</select>
精彩评论