I am using jQuery on method to do a search and populate my div with the search results. I have an input text box which is part of the div's contents. I am using the keyup event to read the text entered and then using ajax to call my server and do the search. When I return the results I populate the text box with the text that has been typed so far. The rest of the content I return is the search results. This is all working fine.
What I want to however is have the focus be placed in my input text box and the cursor placed after the last character typed so that the user can just keep typing and the search results will keep changing with every keystroke. I imagine there is some way to do this with jQuery and JavaScript but I don't know how.
Edit:
Maybe I wasn't clear, but I found the answer at this question: jQuery - Place cursor in input field when link clicked.
Basically all I needed to do was:
var searchBox = $("#search");
searchBox.focus();
searchBox[0].selectionStart = searchBox[0].selectionEnd = searchBox.val().length;
I think you can use select2 plugin. Take a look here, maybe it can help you: http://ivaynberg.github.io/select2/
If I understand correctly, you need to do less rather than more.
You say, "when I return the results I populate the text box with the text that has been typed so far".
Why? The text that has been typed so far is already in the text box, so it should not need to be replaced. By not replacing the text, the user will be able to carry on typing.
There's an additional aspect that you may not have considered ...
The user will almost undoubtedly be able to out-type the ajax responses, so you should take measures to abort an unfulfilled ajax request before issuing a new one. This is made simple by the jQuery jqXHR object returned by $.ajax() (and its shorthand versions) in the form of an abort() method.
Failure to abort could result in the wrong set of search results being displayed against the current text, as the ajax responses are not guaranteed to arrive back in the same order their requests were issued.
Related
I have a search engine for an entity, and it has many filters.
I am required to update the search results when the filters change.
Some filters are selected from dropdowns, others are text inputs.
What is the correct way to implement search on change, when the change can happen frequently as the user types?
Here are some possibilities:
When the input loses focus. The problem: the user might type away some text and wait for the search to work, but it won't.
On each keystroke. The problem is I'll flood the server with requests.
Wait x milliseconds after the last change in the input and then send the request. The problem is the search might become slow for the user.
What is the best approach?
You can either do keydown or keyup for inputs. If it's a dropdown menu you can use onchange.
Personally, I would recommend adding a minimum character limit so you're not hammering your resources.
For example
var foo = document.querySelector("#inputElement");
// Change your event listener to what you need.
foo.addEventListener("keyup", doSomeStuff);
function doSomeStuff(e){
var input = e.value;
// Rest of your function
}
You can learn about event listeners here
I made a Chrome Extension that allowed me to change certain characters if certain keystroke combinations were made to any input or text area field. It works fine as long as what I am typing in is a input or textarea field. However, when I go to a site like FaceBook and try their post or comments field, it doesn't work because those fields somehow don't have textarea tags in their source.
Here is what I currently use.
document.activeElement.onkeydown = function(){ getCharKeyDown(event) };
document.activeElement.onkeyup = function(){ getCharKeyUp(event) };
What would I need to do, to detect if a user is typing in a textarea that doesn't seem to actually be a text area (in plain JavaScript please)?
Thanks.
Thanks to epascarello, I think I've got it sorted. After a bit of reading about the HTMLElement.contentEditable property, I came across Document.execCommand() which seems to take care of all editable elements.
This was the main change I made
function insertAtCursor(myField, myValue) {
document.execCommand('insertHTML', false, myValue);
}
and now I am able to run my functions wherever.
I have successfully bound my jQuery autocomplete with little trouble. When I type in one or two letters, the ajax query gets me the results and the autocomplete shows the items. I am now wanting to trigger the option to "show all" with a button. I know I can use the code
myInput.autocomplete("search");
to trigger the list when bound to a local datasource. When I try to do it on something bound to an ajax populated source, it doesn't trigger the search with an empty string. I wrote the web api to take an optional query string like below:
public IEnumerable<Account> GetAccounts(string query = "")
Typing in a letter works, remote triggering via a button doesn't for some reason.
Ideas?
Have you checked the minlength option?
It must be zero for empty string. Check the below link for detail.
api.jqueryui.com/autocomplete/#option-minLength
This is a bit of a specific request unfortunately.
I have a CMS that allows a user to input text into a tinymce editor for various posts they have made. The editor is loaded via ajax to allow multiple posts to be edited from one page. I want to be able to check if there were edits made to the main text if cancel is clicked.
Currently I get the value of the text from the database during the ajax call, json_encode it, then store it in a javascript variable during the callback, to be checked against later. When cancel is clicked the current value of the hidden textarea (used by tinymce to store the data for submission) is grabbed using jquery.val() and checked against the stored value from the previous ajax call like this:
if(stored_value!=textarea.val())
{
return true
}
It currently always returns true, even if no changes have been made.
The issue seems to be that the textarea.val() uses html entities, whereas the ajax jsoned version doesn't.
the response from ajax in firebug looks like this:
<p>some text<\/p>\r\n<p>some more text<\/p>
the textarea source code looks like this:
<p>some text</p>
<p>some more text</p>
these are obviously different, but how can I get them to be treated as the same when evaluated?
Is there a function that compares the final output of a string or a way to convert one string to the other using javascript?
I tried using html entities in the ajax page, but this returned the string with html entities intact when alerted, I assume because json_encoding it turned them into characters.
Any help would be greatly appreciated.
I really don't believe this is the best way with jQuery, but it works.
var test = "<p>some text</p>";
var dummy = $("<p/>");
test = dummy.text(dummy.html(test));
alert(test);
With prototype you just need to escape the Ajax response before compare it:
ajaxResponse.escapeHTML();
With JQuery I think is a little more different. Try this:
Escaping strings with Jquery
Why dont you try a different approach?
Try to compare textarea.defaultValue and textarea.value before submit your form. If those values are equal the user did not changed anything.
I'm very new to JavaScript and HTML.
I have a simple html form that has some select fields. When the user selects the options from the fields, a function is called that takes the values of the fields, multiples the values against other field values and spits out the results to an input text field named "result".
This is all working great, however I would love a way that instead of outputting the results to a text field, it would output as standard text on the page.
What I did was call the calculate function the tag, within the body, I inserted a document.write(result), then I created a button that calls the calculate function in addition to location.reload().
In Firefox, it works perfectly where it KEEPS the options selected, calculates the results, reloads the page and updates the document.write(result) value on the page.
But in IE or Safari, it resets the select options values to the default settings.
I hope this makes sense and appreciate any help!
how about this:
every time the user selects an option, or makes any sort of a selection, serialize that control, and slap the serialized string to the end of the current window.location, then navigate to it.
also, you will need to add javascript to check the current url, figure out what selection was made, and pro grammatically change the control's values. this way, when the user refreshes the page, the url will contain all of his selections.
got it?
Instead of document.write you could setup an element used specifically to hold the output value much like you do currently with the input element.
In place of the current input element used to output the result..
<span id="calculationResult"></span>
Then to populate that value and avoid reloading the page at all so that your fields maintain current values..
document.getElementById("calculationResult").innerHTML = result;
if you need to append you can always just create text nodes and append to the element which would be preferred anyway.
In order to keep text boxes' content as is, set the button as type="button" and call the calculate function and document.write in onclick. No reload, no mess.