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.
Related
i am complete newbie in jquery/js
I am trying to create web interface for my robotcar and check for multiple keypresses, whenever i release all keys robotcar would stop.
http://jsfiddle.net/gFcuU/1105/
var keys = {};
$(document).keydown(function (e) {
keys[e.which] = true;
keypr();
printKeys();
});
$(document).keyup(function (e) {
delete keys[e.which];
printKeys();
});
function printKeys() {
var html = '';
for (var i in keys) {
if (!keys.hasOwnProperty(i)) continue;
html += '<p>' + i + '</p>';
}
$('#out').html(html);
}
function keypr(){
if (keys[87] && keys[68] == true){
alert('shit works');
}
}
Multiple keypress detection works but if i press W+D stated in function keypr it stops working properly.
Thanks for help
Dude. Your code is working perfectly, but when you do the alert while detecting keypresses, it gets stuck.
Just remove the alert and everything is gonna be fine. if you don't wanna remove the alert i guess you have to remove the object, before displaying the alert.
function keypr(){
if (keys[87] && keys[68] == true){
delete keys[68];
delete keys[87];
alert('shit works');
}
Note: I am quite new to javascript so, apologies if this seems trivial.
I have some code that adds a new container to an existing one on the click of a mouse button.
Using the .click() function, a new class is added, then resized and finally, appended to the parent container.
Is there a way for this also to be done with the 'enter' key?
C.prototype.addSolutionContainerTo = function ($container) {
var self = this;
self.$solutionContainer = $('<div/>', {
'class': 'h5p-guess-answer-solution-container',
}).click(function () {
$(this).addClass('h5p-guess-answer-showing-solution').html(self.params.solutionText);
self.trigger('resize');
}).appendTo($container);
};
return C;
})
One solution I have found is something along the lines of:
$(this).keypress(function (event) {
if (event.keyCode === 13) {
$(this).addClass('h5p-guess-answer-showing-solution').html(this.params.solutionText);
self.trigger('resize');
}
});
However, it doesn't seem to work and won't even throw a console log.
Assuming you want the enter key to work no matter what element is "focused" on the page, you might consider attaching the keypress event to the document, like this:
$(document).keypress(function(event){
if (event.keyCode === 13) $button.click();
});
We have multiple spans inside of a div. We want spans to revert to the original layout when user clicks white space. This is the code:
var whiteSpace = function (){
$(function(){
$('div').on('click',function(e) {
if (e.target !== this)
return;
originalL();
});
});
};
The problem is we have two modes, work mode and set mode, and we want this to only work in the work mode. We change modes with keypress,
$(document).on("keypress", function (e){
if(e.which === 83) {
alert('"Shift + s" was pressed. Start Setup Mode.');
state = "false";
dragResize();
var whiteSpaceDisable = function (){
$(function(){
$('div').off('click',function(e) {
if (e.target !== this)
return;
originalL();
});
});
};
whiteSpaceDisable();
}
if(e.which === 87) {
alert('"Shift + w" was pressed. Start Work Mode.');
state = "true";
dragDropWidget ();
dragResizeDisable();
whiteSpace = function (){
$(function(){
$('div').on('click',function(e) {
if (e.target !== this)
return;
originalL();
});
});
};
whiteSpace();
}
});
When user tries to go to the set mode from the work mode first time, it works. However, when user tries to the same thing second time, it doesn't work. WhiteSpace function persists.
How can we turn this function off in the set mode? By the way, page reload is not an option.Thank you very much!
In your keypress handler, replace:
var whiteSpace = ...
with:
whiteSpace = ...
Right now you're just assigning the other function to a new whiteSpace variable that is scoped to that keypress handler function. If you want to override the previously defined whiteSpace variable, you need to make sure you're actually assigning to that same variable reference, not creating a new one.
Problem solved by placing 'if conditional' inside the originalL function, so it will evaluate before firing. this was the problem.
We just made a 'workMode' variable that can be set to whatever value we need through keypress function. Here's the code that fixed it:
var workMode = "off";
function originalL() {
if (workMode === "on"){
small1O();
small2O();
smalllongO();
smallwideO();
}
};
and at bottom of page, at the keystroke listeners, putting this:
$(document).on("keypress", function (e) {
if (e.which === 83) {
alert('"Shift + s" was pressed. Start Setup Mode.');
workMode = "off";
dragResize();
originalL();
}
;
if (e.which === 87) {
alert('"Shift + w" was pressed. Start Work Mode.');
workMode = "on";
smalllongExpand();
originalL();
dragResizeDisable();
}
I have the following two functions which are fired on different events:
$('.CCB').change(function (event) {
var matches = [];
$(".CCB:checked").each(function () {
matches.push(this.value);
});
alert(matches);
});
which is called when a check box item is checked and
$('#textBox').keydown(function (e) {
var code = e.keyCode ? e.keyCode : e.which;
var st = document.getElementById("textBox").value
if (code != 8) // if backspace is hit don't add it to the search term
{
st = st + String.fromCharCode(code);
}
else
{
st = st.substr(0, st.length - 1)
}
});
which is fired when the user types in a text box. Can I unite them in some way so when any of the actions is fired (either check box check or text box keydown) to get both the array with check box values and the string from the text box, so after that I can perform some custom logic on them?
You can put the logics for both events into functions and then call those functions. For eg.
function checkbox(){
// logic for your operations on checkboxes
}
function keydown(){
// logic for your operations on keydown in textbox
}
And then in your event handlers
var resultFromCheckboxLogic = checkbox();
var resultFromKeydownLogic = keydown();
Please have a look at http://jsfiddle.net/2dJAN/92/
$('input[type=text], input[type=checkbox]').change(function(){
var whole_array = []
var tex_field_value = [];
$('input[type=text]').each(function(){
tex_field_value.push($(this).val())
});
var check_box_value=[];
$('input[type=checkbox]').each(function(){
if($(this).is(':checked') == true){
check_box_value.push($(this).val())
}
});
whole_array = tex_field_value+","+check_box_value
alert(whole_array)
});
This will work on every change of input fields.
Let me know if i understood your requirement correct or not.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Keyboard shortcuts with jQuery
I want to display a popover window using a shortcut key instead of clicking the icon on the toolbar.
Do you have any good idea?
Thank you for your help.
Abody97's answer tells you how to determine if a certain key combo has been pressed. If you're not sure how to get that key combo to show the popover, this is what you need. Unfortunately, Safari makes this needlessly complicated.
In the global script, you'll need a function like the following to show a popover, given its ID and the ID of the toolbar item that should show it:
function showPopover(toolbarItemId, popoverId) {
var toolbarItem = safari.extension.toolbarItems.filter(function (button) {
return button.identifier == toolbarItemId && button.browserWindow == safari.application.activeBrowserWindow;
})[0];
var popover = safari.extension.popovers.filter(function (popover) {
return popover.identifier == popoverId;
})[0];
toolbarItem.popover = popover;
toolbarItem.showPopover();
}
You'll also need code to call this function in your global script's message listener, like the following (this sample does not assume you already have a message listener in place):
safari.application.addEventListener('message', function (e) {
if (e.name == 'Show Popover') {
showPopover(e.message.toolbarItemId, e.message.popoverId);
}
}, false);
Finally, in your injected script, the function that listens for the key combo needs to call dispatchMessage, as below:
safari.self.tab.dispatchMessage('Show Popover', {
toolbarItemId : 'my_pretty_toolbar_item',
popoverId : 'my_pretty_popover'
});
(Stick that in place of showPopUp() in Abody97's code sample.)
Note: If you only have one toolbar item and one popover (and never plan to add more), then it becomes much simpler. Assuming you've already assigned the popover to the toolbar item in Extension Builder, you can just use
safari.extension.toolbarItems[0].showPopover();
in place of the call to showPopover in the global message listener, and omit the message value in the call to dispatchMessage in the injected script.
Assuming your shortcut is Ctrl + H for instance, this should do:
var ctrlDown = false;
$(document).keydown(function(e) {
if(e.keyCode == 17) ctrlDown = true;
}).keyup(function(e) {
if(e.keyCode == 17) ctrlDown = false;
});
$(document).keydown(function(e) {
if(ctrlDown && e.keyCode == 72) showPopUp(); //72 is for h
});
Here's a reference for JavaScript keyCodes: little link.
Here's a little demo: little link. (It uses Ctrl + M to avoid browser-hotkey conflicts).
I believe this could help you: http://api.jquery.com/keypress/
In the following example, you check if "return/enter" is pressed (which has the number 13).
$("#whatever").keypress(function(event) {
if( event.which == 13 ) {
alert("Return key was pressed!");
}
});