jQuery replace function (trigger needed) - php

i got a jQuery function to check a textarea for "valid" urls while someone is typing.
$(".url2").keyup(validNum).blur(validNum);
function validNum() {
var initVal = $(this).val();
outputVal = initVal.replace(/(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,#?^=%&:/~\+#]*[\w\-\#?^=%&/~\+#])$/,"replace this link by bla..");
if (initVal != outputVal) {
$(this).val(outputVal);
}}
});
problem is, that the functions already replaces the url as soon as "http://www.ab" is typed instead of waiting till space is pressed (complete url, waitig for space, replace with this function). I want to achieve, that people can type in a whole url like http://www.example.org/site?id=1&etcetc before it gets replaced. So I think of "space" as a trigger to start the function. Can someone help me or someone got a better idea?
Thank you so much
wordi

If you want space or whitespace chars to trigger validation, use this:
$(".url2").keyup(validateOnWhiteSpace).blur(validNum);
function validateOnWhiteSpace() {
if(event.keyCode == 9 || event.keyCode == 13 || event.keyCode == 32) {
validNum.call(this, arguments);
}
}
function validNum() {
var initVal = $(this).val();
outputVal = initVal.replace(/(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,#?^=%&:/~\+#]*[\w\-\#?^=%&/~\+#])$/,"replace this link by bla..");
if (initVal != outputVal) {
$(this).val(outputVal);
}}
});

I think if you just change your regex you will get what you want
/(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,#?^=%&:/~\+#]*[\w\-\#?^=%&/~\+#])(\s){1}$/
Here is a jsfiddle that seems to work

I can't yet comment on the first thread, but to answer your question about the PHP regexp not working in jQuery, it is because you have ^ at the beginning and $ at the end. The ^ matches the beginning of the string and $ matches the end of the string. Taking it out will allow the regexp to match at any point in the string.
Example:
^abc\d$
Will match:
"abc1"
Will NOT match:
"Zabc1"
Since the "a" is not the first character of the string.

$(".url2").onchange(validNum).blur(validNum);
function validNum() {
var initVal = $(this).val();
outputVal = initVal.replace(/(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,#?^=%&:/~\+#]*[\w\-\#?^=%&/~\+#])$/,"replace this link by bla..");
if (initVal != outputVal) {
$(this).val(outputVal);
}
}

Related

Replace % with - in url PHP

Ok i have one maybe stupid question
On my website i have search options, that is input with GET metod, but when someone enter long seperated word like
I AM SOMETIMES BLANK
i got this in my url
http://www.example.com/search.php?page=1&txtPretraga=I%AM%SOMETIMES%BLANK
I dont know how to change that?
I want clean URL like this
http://www.example.com/search.php?page=1&txtPretraga=I-AM-SOMETIMES-BLANK
I want to change % with - in my ULR
Any ideas?
You can use str_replace in your php code:
http://php.net/manual/en/function.str-replace.php
$search_qry = "Whatever%They%Type";
$replace = str_replace($search_qry, "%", "-");
EDIT:
In the case of your strings - they have spaces, which show up as % in a URL, so use this before you do your $_GET
$search_qry = "Whatever They Type";
$replace = str_replace($search_qry, " ", "-");
EDIT 2
Since this is a $_GET - Javascript will have to be used to clean the string before it's sent. (using jQuery and javascript here)
<script type = "text/javascript">
$(document).ready(function(){
$('.example-input').blur(function(){
var str = $(this).val();
var clean_str = str.replace(" ", "-");
$(this).val(clean_str);
});
});
</script>
This should clean the string in the input box before it's even sent through the get.
or instead of .blur, you can use $('submit-button').click(function(){...
Or, you can use the .htaccess file to do a mod rewrite. But I don't know that well enough.
Ok, i got the fix for the problem :)
This is not question for PHP, it is for Javascript and i wrote this function
<script type="text/javascript">
function provera() {
var x=document.forms["hsearch"]["txtPretraga"].value;
var n=str.replace(" ","-");
}
</script>

Use JavaScript to prevent spacebar?

I have a live search on a site I'm developing. At the moment, it searches the MySql database after the first character is typed, and updates the search for each new character. When Space is pressed as the first character, it displays all entries in the database. I don't want it to do that. I have the following code that I found somewhere that prevents the SPACE character from being typed:
$('input[type="text"]').keydown(function(e){
var ignore_key_codes = [8,32];
if ($.inArray(e.keyCode, ignore_key_codes) >= 0){
e.preventDefault();
}
});
This does what it's meant to do, but not exactly what I want. This will prevent the space bar from working in the text input at all, what I require is that it only prevents the space bar if it's the first character being typed. For example, typing " apples" would prevent the space, but typing "apples oranges" wouldn't.
Is there anything I can try to achieve this?
You can do it easily like this example:
function keyPress(e) {
var e = window.event || e;
var key = e.keyCode;
//space pressed
if (key == 32) { //space
return;
}
searchInDataBase(); //make your ajax call to search in data base etc.
}
If the space key is pressed, you return and dont do nothing, otherwise you continue in your search...
$('input[type="text"]').keydown(function(e){
if (e.keyCode == 32 && $.trim($(this).val()) == ''){
e.preventDefault();
} else {
alert("searching..");
}
});
Demo: http://jsfiddle.net/BerkerYuceer/JJG9M/
Following on from #Florent's comment, when a user types a value into your textbox,check if the trimmed value is != '' if so it should be safe to continue
e.g
if($.trim($txtbox.val()) != ''){ // proceed to do search
}

JS or PHP Add Leading Zero to Decimals

I have a form that I'm trying to automatically enforce decimals in some of the input fields. Basically I would like for the users to not worry about format, but simply have the fields format themselves onBlur.
Here are a few examples of what I'm hoping to achieve:
1.) If a user enters "0.95" nothing is done, because this is the ultimate format I'm going for in the end.
2.) If a user enters ".95" I would like for the field onBlur to change to the above format "0.95". (likewise if they enter ".9" etc)
I have been scouring around on the internet all night long looking for a solution, so this is my last resort! Any help and feedback I can get would be more than appreciated!
Thank you!
Something like this would do it:
document.getElementById('amount').onblur = function() {
if(this.value && !isNaN(this.value)) {
this.value = parseFloat(this.value).toFixed(2);
} else {
this.value = 0;
}
};
jsFiddle
This is nice and concise:
function blurFormatDecimal (e) {
var val = isFinite(this.value) ? +this.value : 0;
this.value = val.toFixed(2);
}
myInput.onblur = blurFormatDecimal;
Use isFinite() instead of !isNaN() because isNaN("Infinity") returns false, but you certainly don't want to accept "Infinity" as valid input.
http://jsfiddle.net/gilly3/NjeQD/
If you need to do this with PHP try:
$formattedAmount = sprintf("%05.2f",$amount);
Here is the php solution:
$formattedAmount = sprintf("%01.2f",$amount);

Chinese character forbid

I have a web form, and I'd want the user while filling the form to not include any Chinese single quotes/double quotes in a textarea, how can I do that ?
You could get the form content and check it against a list of non accepted characters:
$formContent = $_GET["formcontent"];
$badCharacters = array("'", "‘", "“");
$cleanResult = str_replace($badCharacters, "", $formContent);
The bad characters array has the quote signs you dont like (if they are the standard quotes you will need to escape them) then the str_replace function goes through the form data replacing each one with an empty string. You should do proper escaping and security before this of course.
To prevent user from typing into form element you must use client side scripting aka JavaScript.
Simple way is handling the onkeypress event:
<textarea onkeypress="return CheckKey(event);"></textarea>​
And having such code:
var arrForbiddenCodes = [97, 98, 99];
function CheckKey(event) {
var keyCode = event.keyCode || event.which;
for (var i = 0; i < arrForbiddenCodes.length; i++) {
if (arrForbiddenCodes[i] === keyCode)
return false;
}
return true;
}​
This will block characters based on their key code - in the above code, the lower case "a", "b" and "c" letters will be blocked. To find key code of specific character, add alert(keyCode); to the function and just type that character into the textarea.
Live test case.
you could add some javascript that uses a regex to restrict the entry to alpha or alpha and numeric (or any additional characters you want).
<script language="javascript">
function blockChar()
{
var str = document.getElementById('txt').value;
if(str.match(^[a-zA-Z0-9]*$)) {
return true;
}
else {
return false;
}
}
</script>

Regex replace part of url with string only when url doesn't start with http://

Tried to find the answer on stackoverflow but I'm a complete RegEx noob!
All I need (if it's possible) is to match a PDF URL in some HTML and if it doesn't start with http:// add /content/ to the start, if it does start with http:// do nothing.
The regex you want is probably
http://add/content/\S+?\.pdf
Which says it must start with "http://add/content/" then can have anything which isn't a whitespace until it hits a .pdf at the end.
Depending on what language you use you will need to apply this differently. For example in php it would be
preg_match_all('|http://add/content/\S+?\.pdf|',$html,$matches);
if(count($matches)) {
//do stuff with the matches in the $matches array
} else {
//there were no matches of that form
}
Assuming you want to do this with javascript.
var links = document.getElementsByTagName("a");
for(var i = 0; i < links.length; i++){
var link = links[i];
var href = link.getAttribute("href");
if(!/^http/.test(href))
{
link.setAttribute("href", "/content/" + href);
}
}

Categories