简体   繁体   中英

using a function on textbox focus?

I want to add a autocomplete function to a site and found this guide which uses some js code which works really nice for one textbox: http://www.sks.com.np/article/9/ajax-autocomplete-using-php-mysql.html

However when trying to add multiple autocompletes only the last tetbox will work since it is the last one set.

Here is the function that sets the variables for the js script

function setAutoComplete(field_id, results_id, get_url)
{

// initialize vars
acSearchId  = "#" + field_id;
acResultsId = "#" + results_id;
acURL       = get_url;

// create the results div
$("#auto").append('<div id="' + results_id + '"></div>');

// register mostly used vars
acSearchField   = $(acSearchId);
acResultsDiv    = $(acResultsId);

// reposition div
repositionResultsDiv();

// on blur listener
acSearchField.blur(function(){ setTimeout("clearAutoComplete()", 200) });

// on key up listener
acSearchField.keyup(function (e) {

    // get keyCode (window.event is for IE)
    var keyCode = e.keyCode || window.event.keyCode;
    var lastVal = acSearchField.val();

    // check an treat up and down arrows
    if(updownArrow(keyCode)){
        return;
    }

    // check for an ENTER or ESC
    if(keyCode == 13 || keyCode == 27){
        clearAutoComplete();
        return;
    }

    // if is text, call with delay
    setTimeout(function () {autoComplete(lastVal)}, acDelay);
});
}

For one textbox I can call the function like this

$(function(){      
setAutoComplete("field", "fieldSuggest", "/functions/autocomplete.php?part=");
});

However when using multiple textboxes I am unsure how I should go about doing this, here is something I did try but it did not work

$('#f1').focus(function (e) {   
    setAutoComplete("f1", "fSuggest1", "/functions/autocomplete.php?q1=");
}
$('#f2').focus(function (e) {   
    setAutoComplete("f2", "fSuggest2", "/functions/autocomplete.php?q2=");
}

Thanks for your help.

You should be using classes to make your function work in more than one element on the same page. Just drop the fixed ID's and do a forEach to target every single element with that class.

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