How do I get the <select> value to update before printing?

I found a strange thing when printing values.

jQuery(document).ready(function(){

jQuery('#print_btn').on('click', function(){

    var divToPrint=document.getElementById("print_tbl");
    newWin= window.open("");
    newWin.document.write(divToPrint.outerHTML);
    newWin.print();
    newWin.close();
});
});

      

Look at this violin

If you click Print, you will see the value is 1. If you change the value to 2, then click Print again, the value will be 1.

How can I get the print image to reflect the changes?

+3


source to share


3 answers


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); }
// **** below function updated in an EDIT ****
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/

+2


source


You can try using css media queries instead of javascript to determine what is printed. You can start by using the following code

@media print {
    * {
        visibility : hidden;
    }
    .print {
        visibility : visible;
    }
}

      



http://jsfiddle.net/k2mtaob2/2/

Please note that in the above example only World will be printed in the script

+1


source


The problem is you are printing another window. This will print the current window.

jQuery(document).ready(function(){
    jQuery('#print_btn').on('click', function() {
        window.print();
    });
});

      

-1


source







All Articles