Jquery - detect and get the url from text using jquery - javascript

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.

Related

Alternative for keyup function

am working in a popup when we click login a popup opens with fields !!! i want to check username and password with database before login button fired.. used ajax with keyup function for password field!
but keyup is firing for every character typed in password field... but the requirement is after typing password field ajax should be called and result should be displayed... is there any alternative for keyup?
now am getting as "wrong password for every character typed" and after entring correct password it will login,... but i want to show error as wrong password when user completely enters password (if password is wrong)
<script type="text/javascript">
$(document).ready(function() {
$("#upwd").change(function()
//$('#upwd').on('input', function()
//$('#upwd').keyup(_.debounce(doSomething , 500), function() {
var upwd = $("#upwd").val();
var uemail = $("#uemail").val();
var msgbox = $("#status");
//alert(uemail);
//alert(upwd);
//setTimeout(function() {
//if($('#upwd').val() == upwd){
$.ajax({
type: "POST",
url: "checkl_login.php",
data: "uemail="+ uemail,
success: function(msg){
$("#status").ajaxComplete(function(event, request){
if(msg == 'OK') {
msgbox.html(msg);
//return false;
} else {
msgbox.html(msg);
}
});
}
});
return false;
});
});
</script>
error displayed in status id in span......
checkl_login.php code is aalso perfect.....
Try using .focusout() event as shown :-
$("#upwd").on("focusout",function(){
//..your code..
});
and in addition of these events ,use a login button also and check validations on the click of the button.
Use the change event instead of keyup.
IMHO it's better:
to use keyup (it allows to handle any keyboard changes. For example, removing the symbol by backspace)
to handle 'paste' (because user may copy/paste password but not type it)
to validate password if user does not press a key during some period of time (for example, within 1 second) - setTimeout and clearTimeout should help
to abort ajax request if user starts to type when ajax request is in progress
I.e. you may try something like the following:
$(document).ready( function() {
var ajax_h;
var delayMilliseconds = 1000; // i.e. = 1 second
var timeoutId;
function checkAuth() {
if (ajax_h) {
ajax_h.abort();
}
ajax_h = $.ajax(
// PUT YOUR CODE HERE
);
}
$("#upwd").on('keyup paste', function () {
if (timeoutId) {
clearTimeout(timeoutId);
}
timeoutId = setTimeout(checkAuth, delayMilliseconds);
});
});

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();
});
}
},

Enter in search box and redirect to another page

// catch enter code in search form in front page
$('#search').keypress(function (e) {
var str = $('#search').val();
var url = "default.aspx?search=" + str;
if (e.keyCode == 13) {
location.href = url;
}
});
I don't know why this code doesn't work what I expected " When you enter something in input#search, check if it's not empty then redirect to another page ". I try to enter every line in console without checking event, it works!
How can I fix this and why it doesn't work ? Thanks for your consideration time :)
You might try .keyup() instead of .keypress(). Keypress is not an official specification, and can have unfortunate consequences in some browsers.
Put your domain including http for location href to work correctly
// catch enter code in search form in front page
$('#search').keypress(function (e) {
var str = $('#search').val();
var domain = "http://www.yourdomain.com";
var url = domain+"default.aspx?search=" + str;
if (e.keyCode == 13) {
location.href = url;
}
});

Create an autocompleter like the Facebook status update

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
}
});

Categories

Resources