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
}
Related
I want to prevent user to input few characters like ; and \ and /. I now it need jquery to do, but i cant find one
The jquery will used in name. zip code input to prevent such characters etc.
please show me an example as i new to jquery and php
You can use event.which to getting code of pressed key and use return false to preventing enter of character.
$("input").keydown(function(e) {
if (e.which === 186 || e.which === 191 || e.which === 220){
console.log("This character can't entered");
return false;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input />
This should do the job. I hope you can read this simple code:
// select css classes 'input' and assign onKeyDown event to them
$(".input").keydown(function(event) {
// check what key is pressed. dot is not allowed in this case
if ( event.keyCode === 190) {
// prevent event to happen
event.preventDefault();
}
});
On the bottom of this page there is a small table for some codes and also an input field which shows you key code for particular key. Just as a helper, to let you find codes for wished key faster.
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>
I've got a small problem with the following code:
$('#body').keyup(function(){
var i = $('#body').val();
if(i.toLowerCase().indexOf("contact") >= 0){
$('#tosviolation').fadeIn('fast');
$('#sendForm').attr('action','send.php?f=1');
$('.toscontent').html("TOS Breach!");
} else {
$('#tosviolation').fadeOut('fast');
$('#sendForm').attr('action','send.php?f=0');
}
if(i.toLowerCase().indexOf("#") >= 0){
$('#tosviolation').fadeIn('fast');
$('#sendForm').attr('action','send.php?f=1');
} else {
$('#tosviolation').fadeOut('fast');
$('#sendForm').attr('action','send.php?f=0');
}
});
It checks whether #body (textarea) contains the values "contact" or/and "#", and if this textarea does contain said values, it pops up / flashes a div telling the user that they're violating the TOS. With the "#", the box stays there when the user types it, yet when the user types "contact", the box just flashes a few times and goes away, I'm guessing since "#" is 1 char long, and "contact" is 7 chars long, it's something to do with that.
Then again, this is quite strange? I was intending it to just fadeIn() and stay faded in. I didn't mind the flash, because of course, on keyup it'll have to run the function every time the user taps a key, so that's fine, but I can't figure out how to keep it there when the user types "contact" somewhere in the textarea. Also, the other part where the it's using the .attr() is directing the user to send.php, if it does contain "contact","#" -- Then it pushes them to send.php?f=1, and if not, then send.php?f=0 -- #sendForm is the ID of a form tag I have earlier, I assume this already works fine.
Does anyone know how to get the box to stay there once it's pulled up with the data "contact" ?
Try this. Remember, setting the attribute of a form and relying on it for server-side processing is dangerous - the end user can easily fiddle with this before posting. You should validate again with the server and not use any GET variables sent with the form.
$('#body').keyup(function () {
var i = $('#body').val();
if (i.toLowerCase().indexOf("contact") >= 0 || i.toLowerCase().indexOf("#") >= 0) {
$('#tosviolation').fadeIn('fast');
$('#sendForm').attr('action', 'send.php?f=1');
$('.toscontent').html("TOS Breach!");
} else {
$('#tosviolation').fadeOut('fast');
$('#sendForm').attr('action', 'send.php?f=0');
}
});
The problem is that when you're typing "contact", you don't have the "#" symbol. So your first if statement for contact evaluates to true, and fades in #tosviolation. However, the next if statement evaluates to false, so it fades it back out straight away. You'll need to restructure your if statements (likely using an OR condition, rather than two separate if statements) to avoid this.
Something like this should work:
$('#body').keyup(function() {
var i = $('#body').val();
var contact = i.toLowerCase().indexOf("contact");
var atsymbol = i.toLowerCase().indexOf("#");
if (contact >= 0 || atsymbol >= 0) {
$('#tosviolation').fadeIn('fast');
$('#sendForm').attr('action', 'send.php?f=1');
if(contact >= 0) {
$('.toscontent').html("TOS Breach!");
}
} else {
$('#tosviolation').fadeOut('fast');
$('#sendForm').attr('action', 'send.php?f=0');
}
});
Why don't you just check this once, when the field loses focus or before formsubmit? This is easier and cleaner then checking on every keyup event.
I strongly recommend to check the Input on serverside again. simply adding f=1 or f=0 can be manipulated easily. Also think about what happened if the user disabled js.
Currently, when someone just hits the space key and hits enter it will go to the next page but not search anything - I want to prevent the search altogether. What is the best way to accomplish this? I don't want to prevent spaces from being used (ie: How do I fix this?) - I just dont want spaces themselves to allow a search.
Wrap your query variable in an empty condition:
if(!empty(trim($_POST['searchterm']))
{
// do search
}
Use JavaScript and trim leading spaces in the submit (onsubmit) event handler:
var searchField = document.getElementById('search'); // or whatever the id of the field is
if(searchField.value.replace(/^\s+/, '').length === 0) {
return false; // or evt.preventDefault().
}
It should be okay to rely on client-side validation here because if the user wants to fool the search engine then they won't mind being brought to a blank page. If there's an actual server-side problem in allowing this, then perform the same check server-side:
if(!isset($_REQUEST['search']) || !trim($_REQUEST['search'])) {
// Don't perform the search
}
In addition to #AlienWebguy answer you can use JavaScript to do client side validation in order to stop the page from even getting to the back end. Its definitely a good practice to do the validation on the client side AND server side.
Live Demo
form.onsubmit = function(){
if(input.value.replace(/^\s/,"").length === 0){
return false;
}
}
Just take the string, trim the initial and final spaces and check the length; if length is 0, don't submit the form.
If you are procecssing it with php on the backend you can just use trim($input), but for a better user experince use javascript. Set a form validator so it won't submit unless there is something other than whitespace.
<form onsubmit="return verify()">
<input id="foo" name="foo" />
<input type="submit" />c
</form>
<script type="text/javascript">
function verify() {
if (document.getElementById("foo").value.match(/[^\s]/) == null) {
alert('only whitespace');
return false;
} else {
alert('found substance');
return true;
}
}
</script>
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);
}
}