Chezshire Posted May 24, 2010 Share Posted May 24, 2010 Hello to all, First I'd like to thank mjdamato who helped me earlier this weekend (Thank you mjdamato!) I've managed to finish my class assignment and I'm very happy about that, and now I'd like to try to push it to the next level. Currently I have my 'user profile' form's validation method (Is it a method, I'm not sure - still learning - please feel free to correct me on anything that I say which is dumb, stupid, uninformed or just plain wrong ) constructed so that when a user fails to enter data into a required field or if they enter data that will not validate, the javascript flashes a helpful alert, once the user clicks the alert off, focus is returned to the field they need to readdress and a small message appears in the form field which says 'Please Enter Data Here'. I would like it if when someone clicks in the field/begins typing that the message which appears would vanish so that the end user doesn't have to highlight the placed text and delete it as that is something that would be annoying to the end user (at least I believe that that is). I believe that this is possible. I want to do this without using jQuery, Ajax, or php as I don't really know anything about those things and my assignment requires me to do this project without using any of those very helpful tools. So I'm looking for guidance on how I might go about doing something like this. I'm thinking that what I would need to do, is to add a 'sub-function' into the function which onClick changes the value to null (i.e. double quotes with no text/data between the double quotes.) Below is a sample of one of my current called functions which I am using: /** * hasAlphanumeric() uses a regular expression to require both alpha & numeric data * That means it has both a letter and a number or no dice * * Requires alphabetic or numerical data for each character. Will not * accept a space, or any other special character. Good for passwords. * * <code> * if(!hasAlphanumeric(thisForm.Password,"Only alphanumeric characters are allowed for passwords.")){return false;} * </code> * * @param object $fObj input type="text" requiring alphanumeric data * @return true If true, continue to check other items. If false, do not continue * @see isAlpha() * @see correctLength() * @todo none */ function hasAlphanumeric(fObj,msg) {//Uses regular expression for alphabetic check var digitPattern = /[\d]+/; var alphaPattern = /[a-zA-Z]+/; if(digitPattern.test(fObj.value) && alphaPattern.test(fObj.value)) { return true; }else{ alert(msg); // To make text message not appear in field - use empty double quotes! //fObj.value = ""; fObj.value = "Please Fill This Field Out" fObj.focus(); return false; } }//end hasAlphanumeric() How I might revise it (I've tried to call out where I've revised the text by placing a comment using /* comment tag */ - it's at the bottom function hasAlphanumeric(fObj,msg) {//Uses regular expression for alphabetic check var digitPattern = /[\d]+/; var alphaPattern = /[a-zA-Z]+/; if(digitPattern.test(fObj.value) && alphaPattern.test(fObj.value)) { return true; }else{ alert(msg); // To make text message not appear in field - use empty double quotes! //fObj.value = ""; fObj.value = "Please Fill This Field Out" /*This is where I'm trying to delete the text entered by the javascript when the user clicks/begins typing*/ fObj.focus(onClick = fObj.value (""); return false; } }//end hasAlphanumeric() Working Demo (without the implemented revision as the revision doesn't seem to work). http://www.xdesignworks.com/SCC/web150/wk06_fin.shtml JS utility file here http://www.xdesignworks.com/SCC/web150/_js/util.js As always, any help or guidance is very much appreciated, I've tried to think out how to present my request for guidance so that it's clear and respectful of all of you. If anyone has suggestions of how I can improve my method of asking for assistance, please do not hesitate to PM me with suggestions - all are welcome and very much appreciated. Thank you. -Chez Quote Link to comment https://forums.phpfreaks.com/topic/202741-guidance-sought-clear-form-field-when-user-begins-entering-data/ Share on other sites More sharing options...
Psycho Posted May 24, 2010 Share Posted May 24, 2010 Personally, I would not put the instructions (i.e. 'Please Enter Data Here') into the form field. I would have text in a div next to the field that I could hide/show or just change the background color of the field. But, there is a simple solution: On every field you want to do this (or just on all fields), add an onfocus even that will "select()" the field - which will cause all current data in the field to be selected. I would just implement it to occur all the time, regardless if that message is there or not. Function: function selectField(fieldObj) { fieldObj.select(); } On the form fields: <input type="text" name="something" onfocus="selectField(this);" /> Quote Link to comment https://forums.phpfreaks.com/topic/202741-guidance-sought-clear-form-field-when-user-begins-entering-data/#findComment-1062642 Share on other sites More sharing options...
Chezshire Posted May 24, 2010 Author Share Posted May 24, 2010 I. Shall. Explore. This. And then likely come back with oddles of questions and some likely horribly mangled code - thanks for the guidance! Thanks Quote Link to comment https://forums.phpfreaks.com/topic/202741-guidance-sought-clear-form-field-when-user-begins-entering-data/#findComment-1062651 Share on other sites More sharing options...
Ang3l0fDeath Posted May 24, 2010 Share Posted May 24, 2010 Can i ask what was the name of the class your taking / major your in? Quote Link to comment https://forums.phpfreaks.com/topic/202741-guidance-sought-clear-form-field-when-user-begins-entering-data/#findComment-1062702 Share on other sites More sharing options...
Chezshire Posted May 24, 2010 Author Share Posted May 24, 2010 Sure Ang3l0fDeath - Its for a class called 'Intro to JavaScript Programming' I'm taking as part of my graphic arts degree. Due to unfortunate circumstances, I missed the first 3 weeks of class and have largely been struggling to get caught up with everyone because I missed a lot of the informative 'this is a method' 'this is how a function works' etc. etc. etc. But I do have a really great instructor and I'm slowly catching up to where everyone else is. On the bright side i learned that this project isn't due for another week (so i'm actually ahead of the class now, and if that proves to be true I'll be spending much of this week concentrating once more on the lessons that I missed). I go to school in Seattle. -Chez PS 310 angel's of death... gosh the world just suddenly got SOOOOO much bigger Quote Link to comment https://forums.phpfreaks.com/topic/202741-guidance-sought-clear-form-field-when-user-begins-entering-data/#findComment-1062708 Share on other sites More sharing options...
Ang3l0fDeath Posted May 24, 2010 Share Posted May 24, 2010 Well good job catching up, hope you get around to understanding this stuff. I didnt learn javascript until after i learned PHP. Now everything seems like a second language to me except asp & cgi. 310 lol, your the first to say something like that. Also a small suggestion for your page. Set a background & color in the <body> Plus you can style up the page a bit more with css or <style> Only thing i would really suggest to throw in there CSS wise is padding-right:5; or paddingLeft=5; depending on if your using inline style or not. Quote Link to comment https://forums.phpfreaks.com/topic/202741-guidance-sought-clear-form-field-when-user-begins-entering-data/#findComment-1062714 Share on other sites More sharing options...
Chezshire Posted May 24, 2010 Author Share Posted May 24, 2010 Hi mjdamato & Ang3l0fDeath, I was thinking about what mrdamato was suggesting, and i'm trying to figure out how i might change the the background color of the field which the focus is on. That probably would be better then having the little text message appear in my document, so that would mean targeting the field with focus and changing it's style to skyblue for instance but i'm not sure how i would go about that. I don't want to add a hidden div as that means recoding and i'm suppose to work off the class template (which is using tables as it's easier for the whole class to understand and we share our solutions with one another at the end of assignments which is something I like a lot about the class). So would the code be something like this to do such a thingie? function selectField(fieldObj) { var backColor = new String(); backColor = document.getElementByTagName(fieldObj).style.background-color; if(backColor.toLowerCase()=='#eeeee0') { document.getElementByTagName(fieldObj).style.backgroundColor = 'blue'; } else { document.getElementByTagName(fieldObj).style.backgroundColor = '#eeeee0'; } } [code] [code] <input type="text" name="something" onfocus="selectField(this);" /> Also, added some additional padding like Ang3l0fDeath suggested as I can understand the reasoning for that, but I don't understand the reasoning for changing the background color or the body tag -- all my projects in the series have had white backgrounds, and i think that in doing that my projects look better then anyone elses in my class as they all hang together nicely as a series of assignments - and it lets me concentrate more on trying to do good javascript rather then designing. Thanks for the help and guidance -- the above code doesn't work but it's my best guess thus far... uhm.. see i promised mangled code thanks for any help, tips, pointers, throwing of small rocks. - Chez *well maybe not so much thank you for the throwing of small rocks (joking around ) Quote Link to comment https://forums.phpfreaks.com/topic/202741-guidance-sought-clear-form-field-when-user-begins-entering-data/#findComment-1062795 Share on other sites More sharing options...
Psycho Posted May 25, 2010 Share Posted May 25, 2010 Ok, here is a very quick and dirty rewrite that should get you pointed in the right direction. This includes some new functions including one (empty()) which overwrites one of your current functions. The checkForm() function is rewritten and only includes some of the validations as an example. I really don't like that your validation functions are used to perform the alerts and populate the error messages. IMO, a validation function should simply return true/false. This will create a more "full-featured" error handling. It will check for all possible errors and give the user a single error message. It will highlight the field in error with a yellow background, and it will remove the yellow background when accessing the field after an error: 1. Modify the init() function to this function init() {//init places focus on the first form element document.myForm.fName.focus(); //Set onfocus event for all form fields to remove error highlight formObj = document.getElementById('myform'); var fieldCount = formObj.elements.length; for(i=0; i<fieldCount; i++) { formObj.elements[i].onfocus = function() { this.style.backgroundColor=''; } } } 2. Give the form an ID for the above function <form action="http://www.newmanic.com/formtest.asp" method="post" name="myForm" id="myform" onsubmit="return checkForm(this);"> 3. Add the following functions to the head of your document function empty(fieldObj) { //Remove leading.trailing spaces fieldObj.value = fieldObj.value.replace(/^\s+|\s+$/g,''); return (fieldObj.value==''); } //Create global variable var errors; function addError(fieldObj, errorMsg) { errors[errors.length] = ' - ' + errorMsg; fieldObj.style.backgroundColor = 'yellow'; } 4. Modify the checkForm() function like so function checkForm(thisForm) { //check form data for valid info errors = new Array(); if(empty(thisForm.lName)) { addError(thisForm.lName, "Please Enter Your LAST NAME"); } if(empty(thisForm.userName)) { addError(thisForm.userName, "Please Enter Your USERNAME"); } if(empty(thisForm.address1)) { addError(thisForm.address1, "Please Enter Your LEGAL ADDRESS"); } if(empty(thisForm.state)) { addError(thisForm.state, "Please select A STATE"); } if(errors.length>0) { //There were errors alertMsg = 'The following errors occured:\n'; alertMsg += errors.join('\n'); alert(alertMsg); return false; } //if all is passed, submit! return true; } I've also attached a complete file of the modified page. Change extension to htm [attachment deleted by admin] Quote Link to comment https://forums.phpfreaks.com/topic/202741-guidance-sought-clear-form-field-when-user-begins-entering-data/#findComment-1063014 Share on other sites More sharing options...
Chezshire Posted May 25, 2010 Author Share Posted May 25, 2010 Thank you for the guidance mjdamato, it is, I assure your very much appreciated. I have a few questions regarding your guidance if you don't mind. 1. Why do you feel that the function should only return 'true' or 'false' and not also the 'alert'. Is it because that makes that function more 'ultilarian' in that 'Function A' does this, 'Function B' does this and 'Function C' will do this - one function, one purpose. Doing so makes them more like objects (is that the correct term?) so that you can deploy them as needed (in sequence) to get the final behavior you are looking for? I'm just trying to understand your full reasoning (i'm new so understanding the 'why's' of why we do things is very important to me at this stage - I want to learn the correct way of doing things Thank you very much and I look forwards to your answer with much anticipation. Thank you once again (can I say thank you enough?) Uhm.. Thanxs (see that time i used an 'x' ) -Chez Quote Link to comment https://forums.phpfreaks.com/topic/202741-guidance-sought-clear-form-field-when-user-begins-entering-data/#findComment-1063021 Share on other sites More sharing options...
Psycho Posted May 25, 2010 Share Posted May 25, 2010 It does not make them objects. What it does is makes the functions more flexible and useful. And, it makes it much easier to repurpose code. The function name should be appropriate to what it does. For example, if I have a function to check a valid (formatted) email address (e.g. isEmail()), that function should simply return true/false based upon whether the passed value is correctly formatted - nothing more, nothing less. Then you can repurpose that code in other places. Plus, think about this. Currently your code has different functions for validating, empty(), validemail(), vaildZIp(), etc. In each of those functions you have had to implement the same functionality to populate the field with a message. Instead, you should have a single function for populating the message. Because, if you ever wanted to change the behavior when there is an error you would have to change each and every function. Instead, you should simply use those function to do the validatin and return true/false THEN run a common function to perform the actual error handling. Then, if you want to change the error handling you just need to change one function because your validations would stay unchanged. Here is an example based upon your previous functionality, not exatly how I would do it. function showError(fieldObj, errorMsg) { fieldObj.value = errorMsg; return; } function validateForm(formObj) { if(isEmpty(formObj.name)) { showError(formObj.name, "Name is required."); } if(isEmpty(formObj.phone)) { showError(formObj.phone, "Phone is required."); } if(isEmpty(formObj.email)) { showError(formObj.email, "Email is required."); } else if(!validEmail(formObj.email)) { showError(formObj.email, "Email is not a valid format."); } } As you can see, there is a single function for performing the actual error handling. Now let's say you wanted to add functionality to highlight the field. You could simply change that one function function showError(fieldObj, errorMsg) { fieldObj.value = errorMsg; fieldObj.style.backgrounColor = 'yellow'; return; } With your previous code you would have had to change each and every validation function. Quote Link to comment https://forums.phpfreaks.com/topic/202741-guidance-sought-clear-form-field-when-user-begins-entering-data/#findComment-1063087 Share on other sites More sharing options...
Chezshire Posted May 29, 2010 Author Share Posted May 29, 2010 Hello everyone, I'm still playing with this project currently my JavaScript returns the following error message currently: "JavaScript Error: missing ; before statement" Line producing error else(!isOK(thisForm.password)) { addError(thisForm.password, "Please enter a PASSWORD"); } Full JavaScript <script type="text/javascript"> //place local js code here function init() {//init places focus on the first form element document.myForm.fName.focus(); //Set onfocus event for all form fields to remove error highlight formObj = document.getElementById('myform'); var fieldCount = formObj.elements.length; for(i=0; i<fieldCount; i++) { formObj.elements[i].onfocus = function() { this.style.backgroundColor=''; } } } //here we make sure the user has entered valid data function empty(fieldObj) { //Remove leading.trailing spaces fieldObj.value = fieldObj.value.replace(/^\s+|\s+$/g,''); return (fieldObj.value==''); } function isPassword(fieldObj) { //Remove leading.trailing spaces fieldObj.value = fieldObj.value.replace(/^(?=.*[0-9]+.*)(?=.*[a-zA-Z]+.*)[0-9a-zA-Z]{8,16}$/g,''); //fieldObj.focus(); return (fieldObj.value==''); } function isOK(fieldObj) { //Remove leading.trailing spaces fieldObj.value = fieldObj.value.replace(/^(?=.*[0-9]+.*)(?=.*[a-zA-Z]+.*)[0-9a-zA-Z]{8,16}$/g,''); fieldObj.focus(); return (fieldObj.value==''); } function isMatch(fieldObj, fieldObj2) { // This compares the two values for password return (fieldObj.value == fieldObj2.value); } //Create global variable var errors; function addError(fieldObj, errorMsg) { errors[errors.length] = ' - ' + errorMsg; fieldObj.style.backgroundColor = 'orange'; } function checkForm(thisForm) { //check form data for valid info errors = new Array(); if(empty(thisForm.lName)) { addError(thisForm.lName, "Please Enter Your FIRST NAME"); } if(empty(thisForm.lName)) { addError(thisForm.lName, "Please Enter Your LAST NAME"); } if(empty(thisForm.userName)) { addError(thisForm.userName, "Please Enter Your USERNAME"); } if(empty(thisForm.address1)) { addError(thisForm.address1, "Please Enter Your LEGAL ADDRESS"); } if(empty(thisForm.state)) { addError(thisForm.state, "Please select A STATE"); } if(empty(thisForm.zip)) { addError(thisForm.zip, "Please enter a valid US ZIPCODE"); } if(!empty(thisForm.email)) { addError(thisForm.email, "Please enter a valid EMAIL ADDRESS"); } if(empty(thisForm.password)) { addError(thisForm.password, "Please enter a PASSWORD"); } else(!isOK(thisForm.password)) { addError(thisForm.password, "Please enter a PASSWORD"); } else if(!isMatch(thisForm.password, thisForm.password2)) { addError(thisForm.password2, "Please enter a MATCHING CONFIRMING PASSWORD"); } if(empty(thisForm.foundUsHow)) { addError(thisForm.foundUsHow, "Please select how you HEARD OF OUR SERVICES"); } if(empty(thisForm.interestedIn)) { addError(thisForm.interestedIn, "Please select what services you are INTERESTED IN"); } if(empty(thisForm.webTypeDesired)) { addError(thisForm.webTypeDesired, "Please select the KIND OF WEBSITE DESIRED"); } if(empty(thisForm.mailingList)) { addError(thisForm.mailingList, "Can we add you to our MAILING LIST"); } if(errors.length>0) { //There were errors alertMsg = 'The following errors occured:\n'; alertMsg += errors.join('\n'); alert(alertMsg); return false; } //if all is passed, submit! return true; } addOnload(init); //with addOnload() we can add as many functions as we wish to window.onload (one by one)! </script> http://xdesignworks.com/SCC/web150/wk05d_fin.html Thank you for any guidance or help - this has been the most confounding error i've yet had to try to understand as it seems like it should work to me but it doesn't so I'm clearly not getting something. Thank you as always everyone -Chez Quote Link to comment https://forums.phpfreaks.com/topic/202741-guidance-sought-clear-form-field-when-user-begins-entering-data/#findComment-1065027 Share on other sites More sharing options...
Psycho Posted May 29, 2010 Share Posted May 29, 2010 You are putting a condition on an else statement. An "else", by itself, means if all else fails do this. You need change that to an "else if". Also the error on that line is the same as the one before it. So what is different ebtween empty() and isOK()? Quote Link to comment https://forums.phpfreaks.com/topic/202741-guidance-sought-clear-form-field-when-user-begins-entering-data/#findComment-1065080 Share on other sites More sharing options...
Chezshire Posted May 29, 2010 Author Share Posted May 29, 2010 ... Ohhhhhh... Thanks for the guidance mjdamato! I shall dig in to that (I had it working at school, but when i copied the file to my flashdrive I grabbed the wrong version so I'm trying to remember what I did and didn't do to get it working, and this is where I ended up. -- I shall look at what I did with the guidance given (thank you so so so much as always! This is mostly a thank you Mr. Mjdamato notice (laughs) thanks mjdamato - you rock -chez Quote Link to comment https://forums.phpfreaks.com/topic/202741-guidance-sought-clear-form-field-when-user-begins-entering-data/#findComment-1065147 Share on other sites More sharing options...
Chezshire Posted May 31, 2010 Author Share Posted May 31, 2010 I think that I completely forgot to mark this as solved (my bad) -Chez -- thanks to everyone for the help an guidance! Quote Link to comment https://forums.phpfreaks.com/topic/202741-guidance-sought-clear-form-field-when-user-begins-entering-data/#findComment-1065739 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.