Search code examples
javascriptjquerycsshtmlsignaturepad

How to add 2 signature_pad in a same page


I am trying to put 2 signature fields in a same page, using this demo http://szimek.github.io/signature_pad and code at https://github.com/szimek/signature_pad.

How can I put 2 signature pads in the same page, with 2 clear buttons that work for each pad and 1 save button? The save button should show an alert with an error message of which pad is empty, or a success message if both pads are signed.

Here is what I have now (thanks to szimek): http://jsfiddle.net/szimek/ps65Q/

HTML:

var wrapper1 = document.getElementById("signature-pad-1"),
    canvas1 = wrapper1.querySelector("canvas"),
    signaturePad1;

var wrapper2 = document.getElementById("signature-pad-2"),
    canvas2 = wrapper2.querySelector("canvas"),
    signaturePad2;


function resizeCanvas(canvas) {
    var ratio =  window.devicePixelRatio || 1;
    canvas.width = canvas.offsetWidth * ratio;
    canvas.height = canvas.offsetHeight * ratio;
    canvas.getContext("2d").scale(ratio, ratio);
}

resizeCanvas(canvas1);
signaturePad1 = new SignaturePad(canvas1);

resizeCanvas(canvas2);
signaturePad2 = new SignaturePad(canvas2);

JS:

var wrapper1 = document.getElementById("signature-pad-1"),
    canvas1 = wrapper1.querySelector("canvas"),
    signaturePad1;

var wrapper2 = document.getElementById("signature-pad-2"),
    canvas2 = wrapper2.querySelector("canvas"),
    signaturePad2;


function resizeCanvas(canvas) {
    var ratio =  window.devicePixelRatio || 1;
    canvas.width = canvas.offsetWidth * ratio;
    canvas.height = canvas.offsetHeight * ratio;
    canvas.getContext("2d").scale(ratio, ratio);
}

resizeCanvas(canvas1);
signaturePad1 = new SignaturePad(canvas1);

resizeCanvas(canvas2);
signaturePad2 = new SignaturePad(canvas2);

Solution

  • Here is a short example with clear and save buttons.

    The main additions are:

    HTML - add elements for the buttons. These can go anywhere you like, just make sure to give them unique IDs, as this is how you will access them in the JavaScript code.

    <button id="clear1">Clear</button>
    <button id="clear2">Clear</button>
    <button id="save">Save</button>
    

    JS - add functions for clearing and saving, and set the onclick attributes of the buttons you just made to call these functions.

    function clear1() {
        signaturePad1.clear();
    }
    function clear2() {
        signaturePad2.clear();
    }
    function save() {
        if (signaturePad1.isEmpty() || signaturePad2.isEmpty())
            alert("Error: Please sign both pads!");
        else
            alert("Success!");
    }
    
    $("#clear1").click(clear1);
    $("#clear2").click(clear2);
    $("#save").click(save);
    

    It looked like you were already using jQuery, so I used it for setting the onclick attribute, but of course there are other ways to do that.