简体   繁体   中英

jQuery autocomplete variable scope

I'm having an issue with scope of variables in this function. Basically, when a user focuses on a textbox which will have a jQuery dropdown, I want to save the old value in the textbox, if present in order to restore it if required. I have also tried to declare previous outside the function and as window.previous but without success. The problem is that when I use the previous variable from within the .dropdown function I always get it back as undefined

// Delete option allows a user to delete the value directly from the textbox associated with the dropdown.
// Otherwise he will be warned and always forced to make a choice.
// With value will add an extra value to a textbox that has _val apended to the current id
// Create new, if set will open a new confirmation to add the item to the dropdown list
function acomplete(element, source, deleteoption, withvalue, createnew, createtable, createcolumn, retid) {
    var previous;
    // Add arrow as this is a dropdown
    $(element).addClass("dropdown");
    $(element).autocomplete({
        source: source,
        minLength: 0,
        global: false,
        select: function (event, ui) {
            if (withvalue == true) {
                $("#" + $(this).attr("id") + "_val").val(ui.item.thevalue);
                //$("#" + $(this).attr("id") + "_val").trigger("change");
            }
            // Update hidden on select option
            $("#" + $(this).attr("id") + "_id").val(ui.item.id);
            // For items that have change event bound trigger ot so we are updating data in table.
            $("#" + $(this).attr("id") + "_id").trigger("change");
        },
        focus: function (event, ui) {
            // Save old value for backup
            previous = this.value;
        },
        change: function (event, ui) {
            //alert($(this).val());
            if (!ui.item && $(this).val().length > 0) { // Item not selected in the dropdown list
                $.ajax({
                    url: "ajax/check_dropdown_item_exists.php",
                    global: false,
                    method: "POST",
                    data: {
                        table: createtable,
                        colnames: createcolumn,
                        colvals: encodeURI(String($(this).val().toUpperCase())),
                    },
                    success: function (data) {
                        if (data != "TRUE") {
                            // Ask confirm to add new item to table
                            $.confirm('ITEM DOES NOT EXIST! ADD TO LIST?', function (answer) {
                                if (answer) {
                                    $.ajax({
                                        url: "inc/insert_table_field.php",
                                        global: false,
                                        method:"POST",
                                        data: {
                                            table: createtable,
                                            colnames: createcolumn,
                                            colvals: String($(this).val().toUpperCase()),
                                            retid: retid,
                                        },
                                        success: function (data) {
                                            if ($.isNumeric(data)) {
                                                $("#" + $(element).attr("id") + "_id").val(data);
                                                // Set the newly created value in dropdown
                                                //$(element).val(String($(element).val().toUpperCase()));
                                                // And update DB
                                                $("#" + $(element).attr("id") + "_id").trigger("change");
                                            } else {
                                                $.alert(data);
                                            }
                                        },
                                        error: function () {
                                            $.alert('ERROR CREATING THE NEW ITEM!');
                                        }
                                    })
                                } else {
                                    alert(previous)
                                    // NO so blank
                                    $(this).val(previous).focus();
                                }
                            })
                        } else {
                            // Commit change with value that already exists
                            // fecth item id and trigger select event
                            $.ajax({
                                url: "ajax/get_dropdown_item_id.php",
                                global: false,
                                method: "POST",
                                data: {
                                    table: createtable,
                                    colnames: createcolumn,
                                    colvals: String($(element).val().toUpperCase()),
                                    retid: retid,
                                },
                                success: function (data) {
                                    if ($.isNumeric(data)) {
                                        $("#" + $(element).attr("id") + "_id").val(data);
                                        $("#" + $(element).attr("id") + "_id").trigger("change");
                                    }
                                }
                            })
                        }
                    }
                })
            } else {
                $(this).val((ui.item ? ui.item.label : "")); // If empty put back the last one
                if (!ui.item) {
                    if (deleteoption !== true) {
                        this.value = "";
                        $.alert('YOU CAN SELECT FROM DROPDOWN ONLY!');
                        $(element).val(element.oldvalue).focus();
                    } else {
                        $("#" + $(this).attr("id") + "_id").val("");
                        $("#" + $(this).attr("id") + "_id").trigger("change");
                    }
                }
            }
        }
    }).dblclick(function () {
        $(this).autocomplete("search", "");
    }).click(function () {
        $(this).autocomplete("search", "");
    })
}

The problem is that focus don't react on focusing the textbox/input, but instead the result from autocomplete.

That means that when you click in the textbox the function focus will not start only if you select a result.

The best solution for you to get previous would be:

$(your element).click(function() {
   previous = $(this).val()
}

This is from the documentation of jQueryUi Autocomplete:

focus( event, ui )

Triggered when focus is moved to an item (not selecting). The default action is to replace the text field's value with the value of the focused item, though only if the event was triggered by a keyboard interaction. Canceling this event prevents the value from being updated, but does not prevent the menu item from being focused.

focus documentation

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM