Question

I have a jQuery function that prompts for user input which has a callback function to append the text as a new item in a select element onscreen. The problem is that the callback is running multiple times (see below)

The getText() method shows a custom popup with an input element:

function getText(c, cb, elem) {
    var cb = cb || false;
    var elem = elem || false;

    $("#lims_gettext_caption").html(c);
    $("#lims_gettext").show();
    $("#lims_gettext_respond").click(cb);

    $("body").keyup(function(e){
        if (e.keyCode == 27) {
            $('#lims_gettext').hide();
            $("body").unbind("keyup");
        }   
    });
}

getText() is called from a separate method, which runs when the user clicks a specific link on screen:

function PrepareScanner(row) {
    var codes = $("#barcode" + row).size();
    var txt = (codes == 1 ? "first" : "next");

    getText("Please scan " + txt + " barcode", function() {
        var bc = $("#lims_gettext_value").val();
        $("#barcode" + row).append("<option value=1>" + bc + "</option>");
    });

    $("#lims_gettext_value").focus();
    $("#lims_gettext_value").val("");

    return;
}   

What seems to happen is the first time it runs all is well, and a single item is appended to the list. When it runs a second time, TWO items are appended, when it runs the third time, THREE items are appended, and so on. The values of the items added are all correct (ie the value of the input box on screen), I just can't understand why the callback is running multiple times.

I'd appreciate any assistance. I've not been able to find anything that relates specifically to this problem on S.O already.

Thanks

Was it helpful?

Solution

I've managed to figure it out (thanks Kevin B for your input)

It was the following line causing the problem, and had to be unbound in the callback function itself:

$("#lims_gettext_respond").click(cb);

So the adjusted PrepareScanner function is:

function PrepareScanner(row) {
    var codes = $("#barcode" + row).size();
    var txt = (codes == 1 ? "first" : "next");

    getText("Please scan " + txt + " barcode", function() {
        var bc = $("#lims_gettext_value").val();
        $("#barcode" + row).append("<option value=1>" + bc + "</option>");
        $("#lims_gettext_respond").unbind("click");
    });

    $("#lims_gettext_value").focus();
    $("#lims_gettext_value").val("");

    return;
}   
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top