Create an autocompleter like the Facebook status update - javascript

I'm trying to create a div with contenteditable like the Facebook status update. Then I mean I want to show an autocomplete box when the user have written #.
How would you do that. Currently I'm just playing with keypress and check if the keycode = 64. Somehow that works, but it doesn't validate if there's a space before the alfa, or if the user has unfocused the box, then focused it again.
Any ideas? Or do you know about any plugin that works something like that?
Tnx

I'd probably do it with keypress too.
but we need to check the cursor position to check the character before the '#'.
here's the function I used from http://javascript.nwbox.com/cursor_position/cursor.js
function getSelectionStart(o) {
if (o.createTextRange) {
var r = document.selection.createRange().duplicate();
r.moveEnd('character', o.value.length);
if (r.text == '') return o.value.length
return o.value.lastIndexOf(r.text);
} else {
return o.selectionStart;
}
}
then with jquery I wrote this keypress callback function:
txt.keypress(function(event) {
if (event.which == 64) {
var index = getSelectionStart(this)
var prevChar = txt.val().substring(index - 1, index);
// now you can check if the previous char was a space
}
});

Related

submit function - display a warning message

I'm trying to display a warning message when a user types certain text into an input box. The problem is I only want to return false one time so the user can submit the form on the second click even if they don't change the text. I've tried adding a counter but jquery is not remembering the count on a second sumbit click. What is the best way to go about this?
if (email.val().indexOf("gmail") > -1))
{
$('input[name=email]').css('border-color','red');
$("#submit").after('<p>Error - Do you want to use a gmail account?</p>');
return false;
}
I would use a flag to determine if they have already tried to submit, and if they haven't, then you give them the warning and return false:
var triedSubmit = false;
$(/* Your jQuery Object */).click(function() {
if (email.val().indexOf("gmail") > -1))
{
if (!triedSubmit){
$('input[name=email]').css('border-color','red');
$("#submit").after('<p>Error - Do you want to use a gmail account?</p>');
triedSubmit = true;
return false;
}
}
}
Just set up some kind of flag
var flags = {}; // in some higher scope
// then later, in your verification function
if (email.val().indexOf("gmail") > -1 && !flags.warnedGmail) {
$('input[name=email]').css('border-color','red');
$("#submit").after('<p>Error - Do you want to use a gmail account?</p>');
flags.warnedGmail = true;
return false;
}
Why don't you put a class on your text box and remove it in the first failure? Thus when you look for it with jQuery a second time you won't be able to find it it and won't be able to apply the rule. I implmented it like so:
var submit = function()
{
var email = $('.emailFirstTry')
if (email.length > 0 && email.val().indexOf("gmail") > -1)
{
$('input[name=email]').css('border-color','red');
$("#submit").text('Error - Do you want to use a gmail account');
$('.emailFirstTry').removeClass('emailFirstTry');
return false;
}
$('input[name=email]').css('border-color','none');
$("#submit").text('Success!');
return true;
};
You can see it in action on this fiddle right here: http://jsfiddle.net/ozrevulsion/39wjbwcr/
Hope the helps :)

Jquery - detect and get the url from text using jquery

I have textarea and I want to detect when the user will finish TYPING or PASTING a url. I want to catch that url an send it to php.
I looked at many solutions from google, but they all seems to add a anchor tag around the link which I don't want to do.
I tried using this regexp I found in a solution on this website, but it did not work:
/(ftp|http|https):\/\/(\w+:{0,1}\w*#)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%#!\-\/]))?/
the problem with it is that as soon I type something like http://, it will automatically send that string only.
I don't want to write a regexp with finite list of TLDs. What ways can I archive this?
this is the code:
$(document).ready(function() {
$('#write-post-textarea').keyup(function() {
if(isUrl($(this).val())){
//Show the url in an alert box
alert($(this).val());
}else{
//do something if its not a url
}
});
function isUrl(s) {
//var regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*#)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%#!\-\/]))?/
return regexp.test(s);
}
});
Use keyup event along with keycode validation to make sure enter or space button pressed before start validation.
$("#write-post-textarea").keyup(function (e) {
if (e.which == 13 || e.which == 32) { // 32 may be for space bar click
if(isUrl($(this).val())){
//Show the url in an alert box
alert($(this).val());
}else{
//do something if its not a url
}
}
});
I think the problem you have is that whenever you press a key it checks url once. So as soon as you type in something that matches the regexp it sends. You can try set a timer like this:
var timer;
$(document).ready(function() {
$('#write-post-textarea').keyup(function() {
var $this = $(this);
clearTimeout(timer);
setTimeout(function ()}
if(isUrl($this.val())){
//Show the url in an alert box
alert($(this).val());
}else{
//do something if its not a url
}
}, 2000);
});
function isUrl(s) {
//var regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*#)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%#!\-\/]))?/
return regexp.test(s);
}
});
So that timer will be clear when you are typing, and only run the code when you stop.

How to detect new empty line in textarea with Javascript?

I would like to detect a new empty line in a text area and if the user just pressed enter in the text area, without entering any data to return false and echo a message. I have made some research and thought of something like this:
var validatef ....
var code = (e.keyCode ? e.keyCode : e.which);
if (validatef == 'a value here' || code == 13) {
somevarhere.textcontent = 'Message';
return false;
}
else {....}
But it doesn't seem to work.
You can detect an empty line in a textarea by checking for the values:
\r\n (works fine for me) or \n
Just replace the text a value here with \r\n or \n what best suits you.
EDIT:
Check How to count string occurrence in string? to count regex appearances. So you can make a for loop to show the error message on /\s/g.
Hope it helps.
Try this
$('textarea').on('keypress', function(e) {
var val = $('textarea').val();
if (e.which == 13) {
if(! /\S/.test(val)) {
alert("no data");
}
}
});
this alerts no data for each keypress.
This is in jQuery but it will be similar even in plain Javascript
Here is the demo http://jsfiddle.net/TUCx8/
just test if the user pressed enter twice
/\n\n/.test(this.value)
According to the first sentence of the question, this may be one of possible solutions:
var enters = 0;
$('textarea').keypress(function(event) {
if (event.which == 13)
enters++;
else
enters = 0;
if (enters > 1) {
alert('You hit 2 new lines!');
}
});
Live example http://jsfiddle.net/fp6xk/
Another one solution is to check an empty line right before the end of text:
(function(){
$('textarea').keyup(function(event) {
if (/(\r?\n){2}$/.test($(this).val())) {
alert('2 consecutive empty lines at the end!');
}
});
})();
It would work independent of consecutive enter presses.
http://jsfiddle.net/fp6xk/4/

Detect entered character with JavaScript

I'd like to start an action (enabling autocomplete) when user types '#'. I have jQuery available.
Usually on a QWERTY keyboard, it is like this:
$('textarea').live('keydown', function(e) {
if (e.which === 50) {
console.log('# has been entered.');
}
});
However it does not work correctly on an AZERTY keyboard. The keyCode = 50 corresponds to the é~/2 key. To type '#' in AZERTY keyboard, it is AltGr + à#/0 key.
Edit: Autocomplete starts when # is entered, and only after that. Example, when someone enters "Hello #" then it starts, however when he types "Hello #nothing else" the complete won't do anything. Example: http://mrkipling.github.com/jQuery-at-username/ (it works only on QWERTY keyboard).
Use keypress instead of keydown. While keydown relates to every press of a key, keypress relates to the translated characters, so for example a can be different to a while the shift key is pressed, composed characters work, dead-keys work, and other differences in keyboard mappings are handled.
How about checking if # was entered as the last character in the field value?
$("body").on("keyup", "textarea", function(e) {
if (this.value.indexOf("#") == this.value.length - 1) {
console.log("Starting autocomplete");
}
});​
DEMO: http://jsfiddle.net/FKhPW/2/
Use event.key and modern JS, checking for # directly!
No number codes anymore. You can check key directly.
const input = document.getElementById("textarea");
input.addEventListener("keydown", function (event) {
if (event.key === "#") {
// Do something
}
});
Mozilla Docs
Supported Browsers
The only other option that comes to mind would be a timer that checks the content of the text input.
var patt=new RegExp(/^#/);
var charCheck = setInterval(function(){
if (patt.test($("#textInput").val())){
// initiate autocomplete
}
},100);
This code will inspect the contents of the #textInput element and see if it matches the regular expression of a # symbol at the beginning of the string. If it does, the test() function will evaluate to true and you can initiate your autocomplete code.
Here you go working demo: http://jsfiddle.net/LxpQQ/
From my old reply here:
jquery autocomplete using '#'
Hope it will fit you cause :)
code
source: function(request, response) {
if (request.term.indexOf("#") >= 0) {
$("#loading").show();
getTags(extractLast(request.term), function(data) {
response($.map(data.tags, function(el) {
return {
value: el.name,
count: el.count
}
}));
$("#loading").hide();
});
}
},

Custom keyboard / replace keys

I want to change behavior of my keyboard so when user on an input box press key a a = 97 it changes to b 97+1.
I want it for cross browser
jQuery.keypress will get you the event when the users types something, and String.fromCharCode gets you the character + 1. The tricky part is dealing with the selection.
To get the selection, I used the jQuery field selection plugin, and to make sure it doesn't keep jumping back to the end I used this answer to another question. Here is the final code:
$(function() {
$("#target").keypress(function (evt) {
if (evt.which >= 65 && evt.which <= 122) {
var sel = $(this).getSelection();
var val = $(this).val();
var out = val.substring(0, sel.start) + String.fromCharCode(evt.which+1) + val.substring(sel.end, val.length);
$(this).val(out);
$(this).selectRange(sel.start + 1, sel.start + 1);
return false;
}
});
});
jsFiddle
I restricted it to a-zA-Z but you can customize that however you want.
I tested the following in Firefox and Chrome. Using "keypress" allows the use of other keys, and using charCode allows using lower and uppercase letters:
document.getElementById("textbox").addEventListener("keypress",function(event){
event.preventDefault();
this.value+=(String.fromCharCode(event.charCode+1))
},false);
I just now saw the jQuery tag, so you could also do:
$("#textbox").bind("keypress",function(event){
event.preventDefault();
this.value+=(String.fromCharCode(event.charCode+1));
});

Categories

Resources