heisenberg heisenberg - 4 months ago 31
HTML Question

Print button in Javascript

Here's my code :

<table class="table table-hover" id="mytable" >
<thead>
<tr>
<th>Column 1</th>
<th>Column 2</th>
<th>Print</th>
</tr>

<script type="text/javascript">
function initButtonPrint(){
var button = document.getElementById('button-print');
button.onclick = function(e){
print();
grayLine(1);
return false;
}
}

function grayLine(lineId){
var arrayLine = document.getElementById("mytable").rows;
arrayLine[lineId].style.backgroundColor = "silver";
}
</script>

</thead>
<tbody>
<br/>

<?php
for ($i=0; $i<$lineNumber; $i++)
{
?>
<tr>
<td><?php echo $mytable[$i]['Data']['Column 1']; ?></td>
<td><?php echo $mytable[$i]['Data']['Column 2']; ?></td>
<td><input type="button" id="button-print" value="Print"/></td>
</tr>
<?php
}
echo $this->Js->writeBuffer();
?>

</tbody>
</table>

<script type="text/javascript">
initButtonPrint();
</script>


What this code does ?

I put my data from a database into a html table using a for loop and I put a print button in each line. When I click the first print button, the print configuration page opens and the first line is colored grey

arrayLine[lineId].style.backgroundColor = "silver";


What I want to do ?

When I click on a print button, the line is colored grey (or silver here)

The main issue is that I don't know how to tell the javascript which button from which line was pressed. In my code the first line is colored grey because I passed the number 1 into the function

grayLine(1)


Another main issue is that only the first print button from the first line works (only one which opens the print configuration page)

Thanks for your help !

Answer

Ok so I manage to solve my problem and it is ridiculously simple : I deleted the initButtonPrint() and grayLine(lineId) functions which were useless and instead I did this using jQuery (thanks to Gurpreet Janjua) :

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script type="text/javascript">

$(document).ready(function(){
    $('.button-print').click(function(){
        $(this).parent().parent().css('background','grey');
        print();
    });
});

</script> 

The problem was that I declared my button with id instead of class.

Big thank you to Sun Liren, N Muhammed Thamjeed and everyone who replied to me

Comments