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.
Related
Here is a bit of JS/jQuery code that basically goes through and 'picks up' on any fields that are marked with HTML5 attribute 'required' or 'pattern.' It then adds an 'error' class to call attention to it for the user, etc.
$('[required], [pattern').each(function () { // if field is required, we must add .has-error when $(document).ready. We must also add a focus listener to test the pattern and replace .has-error with .has-success, as needed.
if (($(this).attr('required') !== false) && ($(this).val() === "")) {
var formGroup;
formGroup = $(this).closest('.form-group');
formGroup.addClass('has-error'); // .has-error must be added to a .form-group. Use closest() to traverse up DOM starting with $(this) and find the parent .form-group.
$(this).focus(function () { /* .has-error now has focus listener. On focus/blur, we will be testing for an opportunity to have validData, and, subsequently add .has-success */
// We don't want to confuse the user while they are in the field, so let's remove .has-error/.has-success
formGroup.removeClass('has-error'); // upon focus, immediately remove .has-error
formGroup.removeClass('has-success'); // upon focus, immediately remove .has-success
}); // end focus
$(this).blur(function () { // on blur, check for '' val.
if ($(this).val() === "") { // if val() is '', bring back .has-error.
formGroup.addClass('has-error');
// Otherwise, if there is a value, we'll need to check for a pattern.
} else if (!$(this).attr('pattern')) { /* If there is no pattern (we have already established that a value is present), no further testing is required. Go ahead with .has-success. */
formGroup.addClass('has-success');
} else { // If we have made it here, val is not blank, and we have a pattern to go with it.
/* Sometimes a 'general' use fxn. like this might be better served as a fxn. in plugins.js. However, this regExp testing is only used here. Should this change, we can 'externalize' this algorithm */
var regExp = new RegExp($(this).attr('pattern')); // pull the regexp from fg's pattern attrib.
/* Unfortunately, it seems that test() only check to see if the pattern is found, and doesn't account for whether or not there are extraneous characters that shouldn't be there. */
if (regExp.test($(this).val())) { // if match is good, add .has-success {
formGroup.addClass('has-success');
} else { // Pattern doesn't match!
formGroup.addClass('has-error');
} // if-else
} // end if-else if-else
}); // end blur
// if validData = true, add .has-success (and vice-versa).
} // end if
}); // end each
This brings me to the brunt of my PHP question. In most of the examples I have seen for PHP server-side validation, the PHP code is just using a series of if-else statements to 'parse' the form 1 ID at a time, and doing its validation, be it regexp, just required or whatever.
This seems a bit inefficient. It seems that, akin to JS/jQuery, we should be able to build an array of the 'required/pattern' form fields, or otherwise loop through them and then use 'general' messages or string variables to generate error messages to send back to the user.
In other words, instead of doing:
if(trim($name)=="") {
$error = "Your name is required.";
} elseif(trim($email)=="") {
$error = "Your e-mail address is required.";
} elseif(!isEmail($email)) {
$error = "You have entered an invalid e-mail address.";
We should just loop through anything marked 'required' (HTML5) and spit back something like: "The " + #ID + " field is required."
Similarly, we should be able to loop through anything with a 'pattern' attribute, extract the regexp have PHP validate it, and then, utilizing the 'title' (HTML5) attribute, send something back like: "The " + #ID + " field " + .
How can one 'clean up' the PHP code by avoiding multiple if-else statements, and instead taking advantage of HTML5 attributes, for loops, to perform its validation(s)?
Im totally new to javascript and i have no clue how to get this to work... I modified the code a little, but note that line 6 makes no sense. That is the main reason for this post.
<script>
function checkReloading() {
if (window.location.href.split=="?showpastdate") {
document.getElementById("showpastdate").checked=true;
} else {
document.getElementById("showpastdate").checked=false;
}
}
function toggleAutoRefresh(cb) {
if (cb.checked) {
window.location.replace("?showpastdate");
} else {
window.location.replace("");
}
}
window.onload=checkReloading;
</script>
Ok i think this is pretty readable.
First of all window.location.href.split doesn't work because I have to give in the full path. But how can I make this dynamic, so it can be used on more websites? Everywhere I see: window.location.protocol + "//" + window.location.host + "/" + window.location.pathname; but how do I implement this line of code for dynamic webpages? Can someone give me an example?
What I want to achieve with this code is:
When showpastdate is checked, href to ?showpastdate, when at ?showpastdate stay checked so i can use php $_GET on ?showpastdate. This works (when i use static full url). But than...
How do I have to modify this code so that the checkbox remains checked at ?showpastdate untill clicked again, than url goes back to original .php state or other GET var?
Sorry for asking for code writing, but I bet some of u can write this simple lines in 2 minutes while I'm surfing around for 8 hours. Not about to learn javascript, but this really would be a nice option for my program to toggle item showing past date ON/OFF, nicer than having 2 checkboxes, 1 for ON and 1 for OFF :x EDIT: + a submit button #(O _o)#
Thanx in advance.
.split() is a function you can execute on a string object, to split it up in pieces, depending on a parameter provided:
"abcdefg|hijklmnop|qrstuvw".split('|')
would result in a array like this:
["abcdefg","hijklmnop","qrstuvw"]
Now, I am guessing you have added a "?showpastdate" parameter to the url, to change a checkbox's "checked" status.
The easiest way to do that would be:
document.getElementById("showpastdate").checked = (~window.location.href.indexOf("?showpastdate"))
This part: window.location.href.indexOf("?showpastdate") Searches the href for
"?showpastdate"
If the string has been found, it will return a index. if not, it will return -1.
The squiggly in front of it is to convert the -1 or 0 (or higher) to a true / false.
I'm not quite sure what the toggleAutoRefresh() is supposed to do, though
Edit 1
Ah, for the toggleAutoRefresh(), just add this:
if (cb.checked) {
window.location.href.replace("?showpastdate","");
}
instead of that if-else block you have there.
The .replace() function works on a string the same way .split() does. It takes 2 arguments: What to look for, and what to replace it with.
So, for example:
var someString = "words and stuff"
var result = someString.replace(" ","_");
//result will be "words_and_stuff"
Edit 2
These functions should work:
function checkReloading() {
document.getElementById("showpastdate").checked = (~window.location.href.indexOf("?showpastdate"))
}
function toggleAutoRefresh(cb) {
if (cb.checked) {
window.location.href.replace("?showpastdate","");
}else{
window.location.href += "?showpastdate";
}
}
Where are you calling toggleAutoRefresh() from?
Edit 3
What I can conclude from your last comment, is that you want to do something like this:
// If a checkbox named "cb" is checked, and the url contains "?showpastedate"
if ((cb.checked) && ~window.location.href.indexOf("?showpastdate")) {
//Uncheck the checkbox and remove the "?showpastedate" from the url
document.getElementById("showpastdate").checked = false;
window.location.href.replace("?showpastdate","");
} else {
// Else, check the checkbox and add the "?showpastedate" to the url
document.getElementById("showpastdate").checked = true;
window.location.href += "?showpastdate";
}
Note the use of the "~" in front of the indexOf.
If string.indexOf("text") finds "text" at the beginning of a string, like it would in "tekstbooks bla bla bla", it returns 0. First index, starting count at 0.
This zero is interpreted as a false, when implicitly casting it to a boolean. So, if the indexOf were to find a result at the first index, it should (In this situation) return true to indicate a string has been found. That's why we apply the Bitwise NOT ~ to the results of indexOf. -1, indexOf's "Not found" value returns false, and all other results return true.
URL Change Event - JavaScript
http://help.dottoro.com/ljgggdjt.php
I think you could also use the onchange() javascript event.
I'll explain a little bit more.
I have a JQuery datatable, and through CSS I have different <tr classes>. Depending on the information stored in the database, these <tr> get a different class, thus a different color in the datatable.
Now for one <tr class> I'd like to give the user the option to hide/show. I was thinking to do this with a checkbox, and the javascript would parse an url when checked, and remove it when unchecked again. This URL can be used for php to run different queries, if $_GET['parsedurl']: query to show all tables, elseif $_GET['empty']: query for not showing that 1 information.
But this is the worst way to do it. I need to find something to toggle the display: none on or off of the table class, since this is working client-side.
So Im now thinking to keep the parsing of the javascript in an URL and depending on the URL, I run the .php GET to echo out <tr style: display: none> or just simply <tr>
Therefore I need some javascript which does this:
If checkbox is checked, redirect to projectlist.php?showpastdate
When URL = projectlist.php?showpastdate, make checkbox checked.
When URL = projectlist.php?showpastdate and checkbox gets unchecked, redirect to projectlist.php, where the checkbox is unchecked.
I think these triggers are the best options?
With .PHP I'll do:
if (isset($_GET['showpastdate']))
{
<tr style: display: none>
}
else
{
<tr>
}
Maybe someone has an even better solution? I'd like to hear!
Thanks.
EDIT
The javascript I now have is:
<script>
function toggleAutoRefresh(cb) {
if (cb.checked) {
window.location.replace("?showpastdate");
}
// If a checkbox named "cb" is checked, and the url contains "?showpastedate"
if ((cb.checked) && !~window.location.href.indexOf("?showpastdate")) {
//Uncheck the checkbox and remove the "?showpastedate" from the url
document.getElementById("showpastdate").checked = false;
window.location.href.replace("?showpastdate","");
} else {
// Else, check the checkbox and add the "?showpastedate" to the url
document.getElementById("showpastdate").checked = true;
window.location.href += "?showpastdate";
}
}
</script>
After checking the checkbox, it goes to the page projectlist.php?showpastdate and gets unchecked there. When checking again, it goes to projectlist.php?showpastdate?showpastdate. It should remove the ?showpastdate, not add another.
This is could do with PHP too, but I really donĀ“t like a submit button for this checkbox. Just check and execute.
Okay. I got it.
<script>
function toggleAutoRefresh(cb) {
if (~window.location.href.indexOf("?hidepastdate") == 0){
window.location.replace("?hidepastdate");
document.getElementById("showpastdate").checked == true;
}
if (~window.location.href.indexOf("?showpastdate") == 0){
window.location.replace("?showpastdate");
document.getElementById("showpastdate").checked == true;
}
}
</script>
Now the URL gets toggled every time at clicking and PHP does the CSS display work.
Thanks for the effort and for pointing me to the right direction, Cerbrus! Saved me alot of time.
Though it is a very common question. I have one input field in which the data entered must be between 1 and 150.
Problem is I am already using some validations on that. That validation is being used by many other input fields. So I cannot change that. It is the num() function.
On one field mesure I want to add extra functionality. I tried it with validate.
I don't know how to merge these two validations for only one input field using both function in document.ready.
I can do it in either jQuery or PHP.
<input type="text" name='mesure' class="numbersonly" maxlength="3" onblur =" validate()"/>
function num() {
$(".numbersonly").bind('keypress', function(e) {
if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
$("#errmsg").html("numbers please");
return false;
}
});
}
function validate()
{
if( document.form.mesure.value >150 )
{
alert( "out of range!" );
document.form.mesure.focus() ;
return false;
}
}
Why not using onkeypress/onkeyup, check it using the validate function.
But remember that javascript is not the real solution for limitation - People can turn of or change the javascript. Also use php for checking the value.
For example, if your input field that you want to limit has the id #text, you can use
if($('#text').val().length>150){
//do stuff here
}
As you will probably post the entered value to some place in the backend, the real validation must happen in php. There, you can do something like
<?php
if(strlen($_POST['text'])>150){
echo "too long";
exit;
}
//do other backend stuff here
?>
Using javascript for validation is only good in so far as it gives the user immediate feedback whether he did something wrong. However, a client can always see client side code like jQuery/Javascript, so for ultimate validation use php.
Just a quick question regarding this issue i am having. I am using jeditable to edit in place some fields on a page. This is working perfectly. Now I wish to implement some data checking. I have my php code to check the data entered and if its correct, it updates that database, and if it isn't it will return the error. The issue I am having is I want it to spit out the error to tell them but when they click the field again to edit it, it shows the error in the field until a page refresh. What i want it to do is have the same data in the field when they click on it after the error occurs instead of having to refresh the page then click the field again to edit it. Perhaps there is a way to return back the error and pass that into a tooltip of some sort above the field? Of course the way jeditable works is the div is surrounding the field then i have some js calling on my update.php file, this parses what jeditable passes to it and returns a $value to be error checked and by default if it is fine it simply at the bottom of the php "return $value;" to be put back int he field after its been saved in the DB.
Hopefully someone can understand what I am asking here and any assistance would be appreciated.
Easiest way is probably to do some client side validation. Right now you are doing server side validation by checking in PHP when the form is submitted. What are you checking for?Without code it is hard to give you a good example of client side validation.
Basic field checking:
var check_field = $("#field").val();
if (!check_field) { alert("Error message"); } else
{
// submit POST or whatever
}
Edit
Since the MAC address validation algorithm is already written server side, I recommend a separate ajax POST request that calls the checker function. Take the result of that request (true, false) and check it client side. If true, proceed with the update call.
Example:
$("#form").submit(function() {
var mac = $("#macfield").val();
if (!mac) { alert("MAC address can't be empty!"); } else
{
$.POST("checkmacaddress.php", {macval: mac}).success(function(a){
//assuming a comes back as a bool
if (!a) { alert("Invalid MAC!"); } else
{
// if the checker returned true, update the record
$.POST("update.php" ...);
}
});
} });
This doesn't include the checkmacaddress.php but you should be able to handle that if you already have the function on hand.
Hate when I do this, post here then figure out the answer myself...but at least if someone has the same issue they will see it. I found out about the jeditable onsubmit functions...i am using a tooltip to show on hover when editing the field so this will set the tooltip to the error and not submit the data unless its a valid mac.
function isMAC(value) {
teststr = value;
regex=/^([0-9a-f]{2}([:-]|$)){6}$|([0-9a-f]{4}([.]|$)){3}$/i;
if (regex.test(teststr)){
return true;
}
else {
return false;
}
}
$(".edit_mac").editable("edit_mac.php", {
onsubmit: function(settings, data) {
var input = $(data).find('input');
var value = input.val();
if (isMAC(value)) {
return true;
} else {
//display your message
$("#tooltip").html("Bad MAC Address...");
return false;
}
},
indicator : "Saving...",
submitdata: { _method: "put" },
submit : 'Save',
cssclass : "editable",
type : "text"
});
I'm creating a online training 'powerpoint' like series of pages. It will be pretty straight forward and have the pages set out as such:
page1.php
page2.php
page3.php
...
page20.php
I'll be going old school and use an iframe to hide the address bar as people shouldn't be able to catch onto the naming convention and skip ahead. (Its not too serious, so I want to keep it simple).
What I want to do is based on the current page that they are on, say for example page5.php create links to page4.php and page6.html. Obviously without having to code each page manually.
It would be ideal if ths were a javascript function as I dont want the address to show up in the browsers info bar but I'm open to php tricks as well.
Any ideas how to do this?
Use window.location. You can put it in a function like so:
<script type='javascript'>
function goto(url) { window.location=url; }
</script>
<a href='#' onclick='goto("page3.php"); return false;'>Previous</a>
<a href='#' onclick='goto("page5.php"); return false;'>Next</a>
You could also go so far as to use a session variable to hide it, that way you could just do something like this (I hope my PHP skills are still good):
<?php
// At Beginning of first script
start_session();
$MAX_PAGE = 20; // Set this to the highest page number
if(!isset($_SESSION['curpage'])) {
$_SESSION['curpage'] = 1;
} else {
// __EDIT: Added page max and mins.
if($_GET['go'] == 'prev' && $_SESSION['curpage'] > 1) {
$_SESSION['curpage']--;
} else if($_GET['go'] == 'next' && $_SESSION['curpage'] < $MAX_PAGE) {
$_SESSION['curpage']++;
}
}
?>
And then put this in the page where you need it.
<?php
include("page$_SESSION[curpage].php");
if($_SESSION['curpage'] > 1) {
echo "<a href='page.php?go=prev' rel='prev'>Previous</a>";
}
if($_SESSION['curpage'] < $MAX_PAGE) {
echo "<a href='page.php?go=next' rel='next'>Next</a>";
}
?>
Note that Web Crawlers won't be able to do much with this though, when it returns a different page each time.
A little expansion on Pikrass's function, to deal with first/last scenarios:
function goto(url) { window.location=url; }
var curPage = parseInt(location.href.replace(/page([0-9]+)\.php/, ''))
if (curPage <= 1) {
// First page, no 'back' link
document.write('Back');
} else {
var backPage = curPage-1;
document.write("Back");
}
if (curPage >= 9) { // Replace with highest page number
// Last page, no 'next' link
document.write('Next');
} else {
var nextPage = curPage+1;
document.write("Back");
}
URLs are not hidden if you view the source of the page, but they don't show up in the browser's status bar when hovering over the link, as requested.
Edit Updating RegEx with Pikrass' more specific one, to deal with other digits elsewhere in the URL. Thanks Pikrass!
var actuPage = parseInt(location.href.replace(/[^0-9]/, ''))+1;
location.href = 'page'+actuPage+'.php';
That should work if you have no other number in your URLs. If you do, you'll have to change the pattern for replace.
The code is for the next page, change the +1 to -1 for the previous one.
Here is MidnightLightning's version with a better RegExp to get the current page, which works even if you have other numbers in your URLs.
function goto(url) { window.location=url; }
var regPage = /page([0-9]+)\.php/;
var match = regPage.exec(location.href);
var curPage = parseInt(match[1]);
if (curPage <= 1) {
// First page, no 'back' link
document.write('Back');
} else {
var backPage = curPage-1;
document.write("Back");
}
if (curPage >= 9) { // Replace with highest page number
// Last page, no 'next' link
document.write('Next');
} else {
var nextPage = curPage+1;
document.write("Back");
}
I love when an answer is built by several guys. :)
If you can, prefer a PHP code, as suggested. It's much more "clean".
Sounds like you want to use query string variables, so page.php?page=1, page.php?page=2, page.php?page=3 and so on
Why dont you use ajax instead of an iframe?
Well, doesnt matter, you tagged the question jquery so i think you can find usefull using another link attribute to 'tell' js where to redirect.
I mean:
$.(document).ready(funciton(){
//i use the live method becose.. you know, maybe in the future
//you will go with ajax ;)
//live method is avbaiable in jquery 1.3!
$("a.navigation").live('click', function(){
window.location = $(this).attr("rel");
});
});
This let your html markup free from many onclick functions in the <a> tags.
So, your markup will then look something like:
Go to page 1
Go to page 2
<!-- .. and so on.. -->
Or, if you still wanna hide real urls, you can do:
Go to page 1
Go to page 2
<!-- .. and so on.. -->
with this js (maybe not embedded into the page source?)
$.(document).ready(funciton(){
$("a.navigation").live('click', function(){
window.location = 'page' + $(this).attr("rel") + '.php';
});
});
But you'll never be able to completely hide the page urls, if youre planning to use js links.
You could hide them using php, and an hashed strings twin, but i dont know if it worth the game.
Other suggested a regexp way to calculate the pages number and pages links; I will go printing the links via PHP: will let you control the global behavior much better (we dont know how many pages you have, and if theyre numbers is database-related, even the information you gave us would make me think that you have all the page[x].php fisically on your server)