Using this code to plug a signature block into a form.
Using a standard HTML form, this works great (ie, a non-ajax call, but a form submitting to a URL).
But what I am now trying to do, is have the canvas in a bootstrap modal element on the page, which is initially hidden.
I then set the modal to show, and initiate the canvas.
Then – when the form (including the filled signature) is submitted – the form data is saved via ajax
(jQuery).
My issue is that I keep getting errors relating to the canvas/signaturePad not being defined – signaturePad is not defined
when triggering the ajax save.
This is the signature code, included in the bootstrap modal
:
<div id="signature-pad" class="signature-pad">
<div class="signature-pad--body">
<canvas></canvas>
</div>
</div>
This is the jQuery code, for when I launch the modal (which works perfectly – I can sign on the canvas):
$("#ModalActionCost").modal('show');
var wrapper = document.getElementById("signature-pad");
var canvas = wrapper.querySelector("canvas");
var signaturePad = new SignaturePad(canvas, {
backgroundColor: 'rgb(255, 255, 255)'
});
And this is the code when I save the form contents:
$("#trigger").click(function(e){
var dataURL = signaturePad.toDataURL(); <-- this is the line I get the error on.
$("#hiddenSignature").val(signaturePad.toDataURL("image/png").replace("data:image/png;base64,", ""));
var hiddenSignature = $("#hiddenSignature").val();
// ajax call follows.
......
});
Again the error I am getting is: signaturePad is not defined
To try get around this error, I thought I need to initiate the canvas again (call var signaturePad...
) when saving via ajax – which did indeed work, and the pad blob value was sent – but of course I get a blank canvas, seen as it’s been wiped when re define.
I put together a simplified version of the flow of jsfiddle – which DOES seem to work enter link description here, but i cant figure out why my version above does not.
2
Answers
My Solution, for others:
Move the instance of creating the signature_pad - from the function that opens the modal - to
onload
of the page in general:not sure what’s exactly happning with your code, but here is what you can do to solve it.
check your wrapper and canvas vars, see if they’re undefined or null using
console.log(wrapper);
same to the canvas.if they’re actually having values, then in your code, the
signaturePad
variable might be overwritten before the click trigger, or it’s unreachable from within the click event (out of scope).what I suggest to solve it is to give an id to the canvas itself :
then do this :