While epascarello's comment is the best way to do it, you can take this approach by simply adding an attribute selected
to the option corresponding to its parent selectedIndex
. The correct version will then be printed out.
Here are some JS that will do the trick:
function byId(id,parent){return (parent == undefined ? document : parent).getElementById(id);}
function allByTag(tagName,parent){return (parent == undefined ? document : parent).getElementsByTagName(tagName);}
function forEachNode(nodeList, func){for (var i=0, n=nodeList.length; i<n; i++) func(nodeList[i], i, nodeList); }
function setListSelectedAttrib(selectElem)
{
var selectedIndex = selectElem.selectedIndex;
var i, n = selectElem.options.length;
for (i=0;i<n;i++)
{
if (i == selectedIndex)
selectElem.options[i].setAttribute('selected', '');
else
selectElem.options[i].removeAttribute('selected');
}
}
function onPrintClicked(evt)
{
var elemToPrint = byId('print_tbl');
var selectElems = allByTag('select', elemToPrint);
forEachNode(selectElems, eachSelElemFunc);
function eachSelElemFunc(curElem, indexOfCurElem, listOfElems)
{
setListSelectedAttrib(curElem);
}
var newWin = window.open();
newWin.document.write(elemToPrint.outerHTML);
newWin.print();
newWin.close();
}
See the fiddle here: https://jsfiddle.net/jpkz0fyp/1/
source
to share