Abhishek Abhishek - 3 months ago 24
HTML Question

Form field values getting flushed at onclick=window.print()

I was creating an admission form using Html5 and bootstrap.But i wanted to include a feature that user can take a print out of the page before clicking the submit button.So i applied onclick=window.print() at the click of print button.But to the dismay all the field values gets flushed as soon as print button is clicked.

<!DOCTYPE html>
<html lang="en">
<head>
<title></title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>

<div class="container">
<form class="form-inline" id="sunrise" name="sunrise" method="post" action="">
<div class="row">
<div class="form-group">
<label>Father's Name:</label>
<input type="text" class="form-control" name="father" placeholder="">
</div></div> <br/>
<div class="row">
<div class="form-group">
<label>Mother's Name:&nbsp;</label>
<input type="text" class="form-control" name="mother" placeholder="">
</div>
</div>
<br/>
<div class="row">
<div class="form-group">
<label>DOB:</label>
<input type="date" class="form-control" name="dob" placeholder="">
</div>
</div>
<button type="Print" class="btn btn-default" id="print" onclick="window.print()">Print Application</button>
<button type="submit" class="btn btn-default" name="submit" value="submit">Submit</button>


</form>

</div>
</body>
</html>

Answer

Change the print button's invalid type to a valid one.

<button type="Print" class="btn btn-default" id="print" onclick="window.print()">Print Application</button>

to

<button type="button" class="btn btn-default" id="print" onclick="window.print()">Print Application</button>

Because the "Print" type is invalid, the button has the default behavior inside a form, which is submit, that makes the page to reload.