I have a PHP form validation function that I developed in chrome and now will not work in firefox or Opera.
The function checks to see if a section of the form is blank and shows and error message. If there is no error then then the form submits through document.events.submit();
CODE:
function submit_events()
{
//Check to see if a number is entered if the corosponding textbox is checked
if (document.events.dj_card.checked == true && dj_amount.value==""){
//Error Control Method
//alert ('You didn\'t enetr an Amount for DJ\'s Card!');
var txt=document.getElementById("error")
txt.innerHTML="<p><font color=\"#FF0000\"> You didn\'t enetr an Amount for DJ\'s Card!</font></p>";
window.document.getElementById("dj_card_label").style.color = '#FF0000';
//Reset
window.document.getElementById("company_amount_label").style.color = '#000000';
window.document.getElementById("own_amount_label").style.color = '#000000';
}else{
document.events.submit();
}
The document.events.submit();does work across all my browsers however the check statements do not.
If the box is not ticked the form submits. If the box is ticked it does not matter whether there is data in the dj_amount.value or not. The form will not submit and no error messages are displayed.
Thanks guys.
Here are some things I noticed. Not sure if it will solve the problem, but you need to fix some of these; some of them are just observations.
dj_amount is not declared nor referenced; my guess is you mean documents.events.dj_amount
You should put a ; at the end of every statement in javascript, including the end of var txt = document.getElementById("error")
You don't need to escape the string in the txt.innerHTML line; you only need to escape like quotes, such as "\"" or '\'', not "'" or '"'
You don't need the window.document referenced; document will do in almost all cases
EDIT - As Guffa points out, FONT is an old and deprecated element in HTML. It's not the cause of your problems, but modern markup methods mean you don't need it. Consider omitting and applying the style to the paragraph tag instead.
See edits below.
function submit_events() {
//Check to see if a number is entered if the corosponding textbox is checked
if (document.events.dj_card.checked == true && document.events.dj_amount.value == "") {
//Error Control Method
//alert ('You didn't enetr an Amount for DJ\'s Card!');
var txt = document.getElementById("error");
txt.innerHTML = "<p style=\"color: #FF0000;\"> You didn't enter an Amount for DJ's Card!</p>";
document.getElementById("dj_card_label").style.color = '#FF0000';
//Reset
document.getElementById("company_amount_label").style.color = '#000000';
document.getElementById("own_amount_label").style.color = '#000000';
} else {
document.events.submit();
}
}
Consider Firebug so that you can see and log to console javascript errors and messages:
http://getfirebug.com
I believe one of the above answers would solve your problem. For future reference, although it might not be suitable for your project, please know that writing forms and javascript feedback is much easier and faster when you use a library like jQuery.
To have minimal changes in code, just add this line before the first if statement:
var dj_amount = document.forms["events"].elements["dj_amount"];
However your code need serious optimization let us know if you're interested.
Edit: here is the optimization. First the "small" things - instead of whatever you have now for "error" container, have only this instead:
<p id="error"></p>
Now add this CSS to your page:
<style type="text/css">
#error { color: #ff0000; }
</style>
This will take care of the red color, instead of hard coding this in the JS code you now control the color (and everything else) from within simple CSS. This is the correct approach.
Second, right now you are submitting the form as response to onclick event of ordinary button. Better approach (at least in my humble opinion) is having submit button then overriding the form onsubmit event, cancelling it if something is not valid. So, first you have to change the function name to be more proper then have proper code in the function. Cutting to the chase, here is the function:
function ValidateForm(oForm) {
//declare local variables:
var oCardCheckBox = oForm.elements["dj_card"];
var oAmoutTextBox = oForm.elements["dj_amount"];
//checkbox cheched?
if (oCardCheckBox.checked) {
//store value in local variable:
var strAmount = oAmoutTextBox.value;
//make sure not empty:
if (strAmount.length == 0) {
ErrorAndFocus("You didn't enter amount for DJ's Card!", oAmoutTextBox);
return false;
}
//make sure it's numeric and positive and not too big:
var nAmount = parseInt(strAmount, 10);
if (isNaN(nAmount) || nAmount < 1 || nAmount > 1000000) {
ErrorAndFocus("DJ's Card amount is invalid!", oAmoutTextBox);
return false;
}
}
//getting here means everything is fine and valid, continue submitting.
return true;
}
As you see, when something is wrong you return false otherwise you return true indicating the form can be submitted. To attach this to the form, have such form tag:
<form ... onsubmit="return ValidateForm(this);">
And instead of the current button have ordinary submit button:
<input type="submit" value="Send" />
The code will be called automatically.
Third, as you can see the function is now using "helper" function to show the error and focus the "misbehaving" element - this makes things much more simple when you want to validate other elements and show various messages. The function is:
function ErrorAndFocus(sMessage, element) {
var oErrorPanel = document.getElementById("error");
oErrorPanel.innerHTML = sMessage;
document.getElementById("dj_card_label").style.color = '#FF0000';
document.getElementById("company_amount_label").style.color = '#000000';
document.getElementById("own_amount_label").style.color = '#000000';
}
Last but not least, the "new" code also makes sure the amount is positive number in addition to check its existence - little addition that will prevent server side crash.
Everything else is pretty much self explanatory in the function: naming conventions, using local variables.... most important is have as little redundancy as possible and keep the code readable.
Hope at least some of this make sense, feel free to ask for clarifications. :)
You should bring up the error console so that you see what the error actually is.
Lacking that information, I can still make a guess. Try some less ancient HTML code; the parser can be picky about code you add to the page using innerHTML:
txt.innerHTML="<p style=\"color:#FF0000\"> You didn\'t enetr an Amount for DJ\'s Card!</p>";
Related
Hope someone can help with this. I have come across an issue with the application im testing. The developers are using vue.js library and there are a couple of fields which reformat the entered test. So for example if you enter phone number, the field will automatically enter the spaces and hyphens where its needed. This is also the same with the date of birth field where it automatically enters the slashes if the user does not.
So the issue I have is that using both 'setValue()' or 'sendKeys()' are entering the text too fast and the cursor in the field sometimes cannot keep up and the text entered sometimes appears in the incorrect order. For example, if I try to enter '123456789'. Some times it ends up as '132456798' (or any other combination). This cannot be produced manually and sometimes the test does pass. But its flakey.
What I wanted to do was to write a custom command to do something where it enters the string but in a slower manner. For this I need to have control of how fast I want the text to be entered. So I was thinking of something like this where I can pass in a selector and the text and then it will enter one character at a time with a 200 millisecond pause in between each character. Something like this:
let i = 0;
const speed = 200; // type speed in milliseconds
exports.command = function customSetValue(selector, txt) {
console.log(selector);
console.log(txt);
if (i < txt.length) {
this.execute(function () {
document.getElementsByName(selector).innerHTML += txt.charAt(i);
i++;
setTimeout(customSetValue, speed);
}, [selector, txt]);
}
return this;
};
When running document.getElementsByName(selector) in browser console I get a match on the required element. But it is not entering any text. Also note that I added a console.log in there and I was actually expecting this to log out 14 times but it only logged once. So itss as if my if condition is false
I checked my if condition and it should be true. So not sure why its not reiterating the function. Any help is much appreciated.
Also if it helps. I am using the .execute() command to inject javascript which is referenced here: https://nightwatchjs.org/api/execute.html
And the idea on this type writer is based on this: https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_typewriter
We ended up taking a different approach much simpler. Wanted to post here in case anyone else ever needs something similar
exports.command = function customSetValue(selector, txt) {
txt.split('').forEach(char => {
this.setValue(selector, char);
this.pause(200); // type speed in milliseconds
});
return this;
};
I have a web page with a form on it. The "submit" button is supposed to remain deactivated until the user fills in all the necessary fields. When they fill in a field, a checkmark appears next to it. When all the checkmarks are there, we're good to go.
A checkmark might be set by code like this:
if (whatever) checkLocation.innerHTML = CHECKMARK;
Here's the code I'm using to do the final check. It just loops through all the locations where there may be checkmarks. If it finds a location without a mark, it disables the submit button and leaves. If it gets through them all, it activates the button and returns true.
function checkSubmitButton() {
var button = document.getElementById(SUBMIT_BUTTON);
for (var i=0; i<CHECK_LOCATIONS.length; i++) { // should be for-each, but JS support is wonky
var element = document.getElementById(CHECK_LOCATIONS[i]);
console.log(CHECK_LOCATIONS[i] +": " +element.innerHTML);
// if found unchecked box, deactivate & leave
if (element.innerHTML != CHECKMARK) {
button.disabled = true;
return false;
}
}
// all true--activate!
console.log("ACTIVATING BUTTON!");
button.disabled = false;
return true;
}
Here's the problem: this works so long as the const CHECKMARK contains something simple, like "X". But specs call for a special HTML character to be used: in this case ✓, or ✓. When I do the comparison (in the if line) it ends up comparing the string "✓" to the string "✓". Since these two are not equal, it doesn't recognize a valid checkmark and the button never activates. How can I compare the contents of the HTML element my constant? (And hopefully make the code work even if down the road somebody replaces the checkmark with something else.)
Thanks.
There is no problem with the check character and it behaves exactly like the X character. The problem is, that your html have the checkmark character stored as html entity in hex string. If you compare checkmark to checkmark it works just fine: https://jsfiddle.net/m7yoh026/
What you can do in your case is to make sure the CHECKMARK variable is the actuall checkmark character, not the html entity.
Other option is to decode the html entity: https://jsfiddle.net/m7yoh026/3/
var CHECKMARK = '✓'
var decoded_checkmark = $('<textarea />').html(CHECKMARK).text();
console.log($('div')[0].innerHTML)
if ($('div')[0].innerHTML == decoded_checkmark) {
$('body').append('checkmark recognized<br>')
}
You can convert a character to its HTML entity equivalent like so:
var encoded = raw.replace(/[\u00A0-\u9999<>\&]/gim, function(i) {
return '&#'+i.charCodeAt(0)+';';
});
Well, here's what I ended up doing: I made a function called encodeHtml() that takes a character or string, writes it to a brand new div, and then returns what's contained in that div:
function encodeHtml(character) {
var element = document.createElement("div");
element.innerHTML = character;
return element.innerHTML;
}
Then I can compare to what it returns, since it automatically changes "✓" to "✓", and will work with any unforeseen changes to that character. It's a bit of a kludge, but it works. (It's still not clear to me why JavaScript does this automatic conversion...but there are many design choices in which JavaScript mystifies me, so there you go.)
Thanks all for the help.
I have a script that is taking too long to run and that is causing me This error on ie : a script on this page is causing internet explorer to run slowly.
I have read other threads concerning this error and have learned that there is a way to by pass it by putting a time out after a certain number of iterations.
Can u help me apply a time out on the following function please ?
Basically each time i find a hidden imput of type submit or radio i want to remove and i have a lot of them . Please do not question why do i have a lots of hidden imputs. I did it bc i needed it just help me put a time out please so i wont have the JS error. Thank you
$('input:hidden').each(function(){
var name = $(this).attr('name');
if($("[name='"+name+"']").length >1){
if($(this).attr('type')!=='radio' && $(this).attr('type')!=='submit'){
$(this).remove();
}
}
});
One of the exemples i found : Bypassing IE's long-running script warning using setTimeout
You may want to add input to your jquery selector to filter out only input tags.
if($("input[name='"+name+"']").length >1){
Here's the same code optimised a bit without (yet) using setTimeout():
var $hidden = $('input:hidden'),
el;
for (var i = 0; i < $hidden.length; i++) {
el = $hidden[i];
if(el.type!=='radio' && el.type!=='submit'
&& $("[name='" + el.name + "']").length >1) {
$(el).remove();
}
}
Notice that now there is a maximum of three function calls per iteration, whereas the original code had up to ten function calls per iteration. There's no need for, say, $(this).attr('type') (two function calls) when you can just say this.type (no function calls).
Also, the .remove() only happens if three conditions are true, the two type tests and check for other elements of the same name. Do the type tests first, because they're quick, and only bother doing the slow check for other elements if the type part passes. (JS's && doesn't evaluate the right-hand operand if the left-hand one is falsy.)
Or with setTimeout():
var $hidden = $('input:hidden'),
i = 0,
el;
function doNext() {
if (i < $hidden.length) {
el = $hidden[i];
if(el.type!=='radio' && el.type!=='submit'
&& $("[name='" + el.name + "']").length >1) {
$(el).remove();
}
i++;
setTimeout(doNext, 0);
}
}
doNext();
You could improve either version by changing $("[name='" + el.name + "']") to specify a specific element type, e.g., if you are only doing inputs use $("input[name='" + el.name + "']"). Also you could limit by some container, e.g., if those inputs are all in a form or something.
It looks like the example you cited is exactly what you need. I think if you take your code and replace the while loop in the example (keep the if statement for checking the batch size), you're basically done. You just need the jQuery version of breaking out of a loop.
To risk stating the obvious; traversing through the DOM looking for matches to these CSS selectors is what's making your code slow. You can cut down the amount of work it's doing with a few simple tricks:
Are these fields inside a specific element? If so you can narrow the search by including that element in the selector.
e.g:
$('#container input:hidden').each(function(){
...
You can also narrow the number of fields that are checked for the name attribute
e.g:
if($("#container input[name='"+name+"']").length >1){
I'm also unclear why you're searching again with $("[name='"+name+"']").length >1once you've found the hidden element. You didn't explain that requirement. If you don't need that then you'll speed this up hugely by taking it out.
$('#container input:hidden').each(function(){
var name = $(this).attr('name');
if($(this).attr('type')!=='radio' && $(this).attr('type')!=='submit'){
$(this).remove();
}
});
If you do need it, and I'd be curious to know why, but the best approach might be to restructure the code so that it only checks the number of inputs for a given name once, and removes them all in one go.
Try this:
$("[type=hidden]").remove(); // at the place of each loop
It will take a short time to delete all hidden fields.
I hope it will help.
JSFiddle example
jSignature is having canvas and it has a class. How can I validate jSignature whether I have drawn something or not ?
I have added one bind for click event.
$sigdiv.bind('click', function(e) {
$("#num_strok").val(parseInt($("#num_strok").val()) + 1);
});
Problem is even I click some corner also num_strock get increases. And for some dragging it will not increase.
I have tried in Google whether it has any built in isEmpty function is there or not. But I have not found anything.
if( $sigdiv.jSignature('getData', 'native').length == 0) {
alert('Please Enter Signature..');
}
Very late to the party... So I wanted to give some input on my findings, each related to
using $("#sigDiv").jSignature('getData', 'putSomethignInHere') function to validate the a signature is present.
Here are the options I have examined for the second attribute passed into the jSignature function:
native returns an object of objects .length == 0 when the sig box is empty, but .length > 0 when there is something in the sig box. If you want to know how many strokes just use the length of this object.
NOTE: According to the jSignature documentation:
"Stroke = mousedown + mousemoved * n (+ mouseup but we don't record that as that was the "end / lack of movement" indicator)"
base30 also returns an object. Here I looked at the information in the second index position of this object.
x = $("#sigDiv").jSignature('getData', 'base30')[1].length > 0 ? TRUE : FALSE Here x would yeild TRUE if the box has been signed and FALSE when the jSig box is left untouched.
In my case, I used the base30 attribute for validating signature complexity, not just "did the end user draw something?".
x = $("#sigDiv").jSignature('getData', 'base30')[1].length > {insertValueHere} ? TRUE : FALSE. To validate the end user actually signed in the box and gave more than a simple '.' of small 'x'. The return value of the second index yielded from base30 gets larger as the complexity. Thus, if the user did enter just a dot,
x = $("#sigDiv").jSignature('getData', 'base30')[1].length would be about 5. The yielded value just get larger and larger the more the end user draws in the box. The highest lenght I recorded during my testing was 2272. And I scribbled and scribbled in the box for all of 15 secounds.
According to the jSig documentation:
base30 (alias image/jSignature;base30) (EXPORT AND IMPORT) (VECTOR) data format is a Base64-spirited compression format tuned for absurd compactness and native url-compatibility. It is "native" data structure compressed into a compact string representation of all vectors.
image- this is a choice I would avoid for validation. It produces an object with a long string in the second index position. The last one I measured was 672 characters long. Using image produces a string regardless whether the sig box is blank or used. And to make things more unuseful, the string produced is different for a blank signature box in Chrome verse a blank signature box in FF Developer. I'm sure the image value has a use, but just not validation.
svgbase64 - this is similar to image with exceptions. Unlike image, using svgbase64 produces a long -yet shorter- string in the second position. Also, this string IS the same when I performed the Chrome verse FF Developer check. This is where I stopped my testing. So I assume you can use svgbase64 for validation.
These are my conclusions, yours may vary. Please don't hold my low reputation against me.
According to the jSignature website there is a getData function in the API. If you use the getData function on an empty signature area as reference, you could then use getData whenever you want and compare it to the empty reference. You would then be able to tell if something has been written in the signature area.
This is just a guess from my part, as I haven't used this script, but I think something like this would be able to work.
EDIT
I also found this on the website
The dom element upon which jSignature was initialized emits 'change'
event immediately after a stroke is done being added to the storage.
(In other words, when user is done drawing each stroke. If user draws
3 strokes, this event is emitted 3 times, after each stroke is done.)
Here is how you would bind to that event:
$("#signature").bind('change', function(e){ /* 'e.target' will refer
to div with "#signature" */ })
Event is emitted asynchronously through a "thread" ( setTimeout(..., 3) ) so you don't need to wrap your event handler into "thread" of any kind, as jSignature widget will go on and will not be waiting for you to be done with your custom event handler logic.
Couldn't you just set a flag variable that gets set to true on the first change event? That would indicate that something is written into the area
You can check the base30 vector if any points are there.
var isSignatureProvided=$sigdiv.jSignature('getData','base30')[1].length>1?true:false;
This worked for me, part using roch code :
it basically assigns the signature to a hidden textarea before submitting for validation:
<div id="signatureparent">
<div id="signature"></div>
<label for='signature_capture' class='error'></label>
</div>
<span style="visibility:hidden;">
<textarea name="signature_capture" class="required" id="signature_capture"></textarea>
</span>
<script>
$(document).ready(function(){
$('#submit').click(function() {
var isSignatureProvided=$('#signature').jSignature('getData','base30')[1].length>1?true:false;
if (isSignatureProvided) {
var $sigdiv = $("#signature");
var datapair = $sigdiv.jSignature("getData", "svgbase64");
var data = $('#signature').jSignature('getData');
$("#signature_capture").val(data);
}
});
});
</script>
Unfortunately no of existing answers worked for me. On my site I have two methods of inputting a signature: manual and jSignature('importData', imgBase64)
Testing of jSignature('getData', 'native') worked only for manual drawing. And nothing worked for the image way.
The solution appeared to be simple. Just test the canvas element. It probably won't work for IE9 but who cares. Here is it in TypeScript:
isSignatureBlank() {
var canvas = <any>$('#signatureElem').find("canvas")[0];
if (!canvas) return true;
this.emptyCanvas = this.emptyCanvas || document.createElement('canvas');
this.emptyCanvas.width = canvas.width;
this.emptyCanvas.height = canvas.height;
return canvas.toDataURL() == this.emptyCanvas.toDataURL();
}
Adopted from here: How to check if a canvas is blank?
Search the code in your javascript file. Check when they are hiding 'Undo Stroke' block
t.dataEngine.data.length
That will help you finding how many stroke is made to the signature panel.
Maybe try something like this (assuming your signature fields are of class 'signature')...
$('.signature').each(function (index) {
var datapair = $(this).jSignature("getData", "svgbase64");
if (datapair[1].length > 1000 ) {
// Signature is valid; do something with it here.
}
});
The best answer:
if($sigdiv.jSignature('getData', 'native').length == 0) {
alert('Please Enter Signature..');
}
produced the following error:
$sigdiv.jSignature(...) is undefined
So I would suggest using:
if(typeof($sigdiv.jSignature('getData', 'native')) != 'undefined') {
alert('Please Enter Signature..');
}
What would a JavaScript script be that, on submit, gets all form elements with class="required" and if they're empty, displays an alert box, "you must fill out so-and-so"?
I was thinking of an if-else, and in the if section we would get a while that loops through all the class=required elements, and the else would submit the form.
There are many many JavaScript libraries on the internet that do exactly this.
Try this one:
http://www.position-absolute.com/articles/jquery-form-validator-because-form-validation-is-a-mess/
Or try a Google search for JavaScript Form Validation.
It is fairly easy to loop over the elements of a form and check that those with a certain class have a value that meets certain criteria:
<form name="f0" onsubmit="return validate(this);">
<input name="inp0" class="required" >
<input name="inp2" class="required" >
<input type="submit">
</form>
<script type="text/javascript">
var validate = (function() {
var reClass = /(^|\s)required(\s|$)/; // Field is required
var reValue = /^\s*$/; // Match all whitespace
return function (form) {
var elements = form.elements;
var el;
for (var i=0, iLen=elements.length; i<iLen; i++) {
el = elements[i];
if (reClass.test(el.className) && reValue.test(el.value)) {
// Required field has no value or only whitespace
// Advise user to fix
alert('please fix ' + el.name);
return false;
}
}
}
}());
</script>
The above is just an example to show the strategy.
Using an alert is less than optimal, usually an area is set aside adjacent to the required fields so that error messages can be written there to direct the user's attention to the invalid fields. You can also set all the error messages in one go, then return, rather than one at a time.
Edit—updating multiple errors
Have an element adjacent to each control to be validated with an id like the element's, so if an input is called firstName, the error element might have an id of firstName-err. When an error is found, it's easy to get the related element and put a message in it.
To do all at once, use a flag to remember if there are any errors, say "isValid" that is set to true by default. If you find any errors, set it to false. Then return it at the end.
Using the example above, the HTML might look like:
<input name="firstName" class="required" >
<span id="firstName-err" class="errMsg"></span>
Errors for firstName will be written to firstName-err.
In the script, if an error is found:
// At the top
var isValid = true;
var errEl;
...
// When entering the for loop
el = elements[i];
errEl = document.getElementById(el.name + '-err');
// when error found
isValid = false;
if (errEl) errEl.innerHTML = '... error message ...';
// else if error not found
// remove message whether there is one or not
if (errEl) errEl.innerHTML = '';
...
// At the end
return isValid;
You can also use a popup to show the errors, however that is really annoying and the users must dismiss the popup to fix the errors. Much better to just write next to each one what is wrong and let the user fix things in their own time.