Posts Tagged JavaScript

Prevent double-click on HTML form

How many users are still double-clicking when they visit a website? It is not really a problem with links, but it could be with buttons.
Let’s take, for example, a ‘contact us’ form and a submit button which will send the content of the form by email to the website administrator. What happens if a user double-click on the submit button? The form will be submitted twice and in consequence two emails will be sent instead of one.

There are multiple ways to fix this problem. The solution I will explain below is to disable the submit button once it has been pressed. In that way, even if the user double-clicks on it, the form will be submitted only once! :)

To disable the submit button once it has been pressed, you simply need to add the following JavaScript code in the onclick attribute of your button tag:

this.disabled=true;this.form.submit();

For example:

<input name="submitButton" id="submitButton" type="submit" value="Submit" onclick="this.disabled=true;this.form.submit();" />

The code above will work fine if you don’t have an onsubmit attribute in your form tag. But, if you have one, you will notice that the function this.form.submit() will not execute the content of the onsubmit attribute. In that case, you need to force the call as shown below:

this.disabled=true;if(this.form.onsubmit()){this.form.submit();}else{this.disabled=false;}

However, it is recommended to move whatever you have in the onsubmit attribute in the button onclick, such as:

this.disabled=true;if(validateForm()){this.form.submit();}else{this.disabled=false;}


NOTE:
If in your code, you are using the following to check if the form has been submitted:

if (isset($_POST['submitButton'])) { echo "Form submitted!"; }

It will need to be replaced by the following:

if ($_SERVER['REQUEST_METHOD'] == "POST") { echo "Form submitted!"; }

, , , , ,

No Comments

Detect if JavaScript is enabled

Because of the emergence of Ajax, people don’t disable JavaScript much nowadays.
I don’t know the percentage of people having disabled JavaScript. It is likely under 5%. But if you have a website visited by millions of visitors every month, even 1% is matter!

This is why I wrote the following code:

<noscript>JavaScript is DISABLED.</noscript>
<span id="displayIfJavaScript" style="display:none">JavaScript is ENABLED.</span>

<script>
document.getElementById('displayIfJavaScript').style.display = "block";
</script>

The text under the noscript tag will be displayed if JavaScript is disabled or not supported. The text under the span tag is not displayed by default and will be showed using JavaScript, this is why we can be sure JavaScript is enabled in that case.
You can obviously change the content of the noscript and span tags. You could, for example, hide a form which uses JavaScript validation to non-JavaScript users by putting the HTML code of the form under the span tag.

Please see below the above script in action:

, ,

No Comments

Close ModalPanel if no error

It has been a very long time I wrote this code, but I thought I would share it with you as it is quite useful.

If like me, you are an adept of RichFaces, you might have already seen and used the modal panel functionality. By default, a modal panel is used to display a message, but what if you actually want to display a form within it? How nice would it be if, for example, you could put your login form in a modal panel instead of opening a new page?

With the following steps, you will be able to achieve this:

  • First, get the maximum severity in the message queue:
    <a4j:outputPanel ajaxRendered="true">
        <h:form style="display:none" id="maximumSeverityForm">
            <h:inputHidden id="maximumSeverity"
                value="#{facesContext.maximumSeverity.ordinal}"/>
        </h:form>
    </a4j:outputPanel>
    

    This form has to be placed on all your pages using an include for example. This form will basically get refreshed on every postback and will contain the maximum severity in the message queue or null if the queue is empty.

  • Create a JavaScript method which reads the maximumSeverity hidden field:
    function ajaxRequestContainsErrors() {
        return document.getElementById("maximumSeverityForm:maximumSeverity").value > 0;
    }
    

    This method has to also be included in all the pages.

  • Finally, use the following code for the “Submit” button in your form:
    <a4j:commandButton action="#{userBean.loginAction}" value="Submit" oncomplete="if (!ajaxRequestContainsErrors()) {Richfaces.hideModalPanel('loginModalPanel');}"/>
    

    This button is actually checking if there is no error before closing the modal panel.

, , ,

No Comments

Validate file size prior upload

If I ask you what is the most complex thing in HTML, what would you reply?
For me, it would be the file upload (or maybe character encoding, but this is not the topic! :P ).

One of the problem around the file upload functionality is that there is, no matter what, a file size limit set on the server. The limit could be 100Kb such as 100Mb depending on the configuration of the server.
But what happens if the user tries to upload a file bigger than the limit?
It’s simple, the file is going to be uploaded on the server until the limit is reached. Once it happens, the server returns an error message to the client.
Well, this is not ideal!
Indeed, depending on the connection speed of the user, the error message could be displayed a few minutes later. And you know how impatient users are! ;)

So obviously, the solution would be to validate the file size before the upload starts.
To do that, we can simply use the fileSize Javascript function against the upload field.
But, surprising enough, this function doesn’t work on Internet Explorer! :evil:

And the only solution I found to get the file size with IE was using ActiveX:

var oas = new ActiveXObject("Scripting.FileSystemObject");
var e = oas.getFile(document.forms[0].file.value);
var size = e.size;

Finally, here is the whole Javascript function to validate the file size:

function validateFileSize(file, maxSize) {
	if (navigator.appName=="Microsoft Internet Explorer") {
		if (file.value) {
			var oas = new ActiveXObject("Scripting.FileSystemObject");
			var e = oas.getFile(file.value);
			var size = e.size;
		}
	} else {
		if (file.files[0]!=undefined) {
			var size = file.files[0].fileSize;
		}
	}
	if (size!=undefined && size > maxSize)
		return false;
	return true;
}

with file the file input field to validate and maxSize the maximum size in bits.

For example, you can call this function as follow:

validateImageSize(document.forms[0].file, 500000)


I successfully tested this code on:

  • Google Chrome 6;
  • Firefox 3.6;
  • Internet Explorer 6;
  • Internet Explorer 7.

, , , , , ,

No Comments

Validate your EAN barcode

On one of the applications I am working on, I had to validate an EAN (European Article Number) barcode.
This application is mostly using JavaScript validation so I asked my friend Google to find me a JavaScript method which would check my EAN barcode.
It found validators in different languages but none in JavaScript. :(

Because one is never better served than by oneself, I decided to write it myself and share it with you. ;)

function checkEan(eanCode) {
	// Check if only digits
	var ValidChars = "0123456789";
	for (i = 0; i < eanCode.length; i++) {
		digit = eanCode.charAt(i);
		if (ValidChars.indexOf(digit) == -1) {
			return false;
		}
	}

	// Add five 0 if the code has only 8 digits
	if (eanCode.length == 8 ) {
		eanCode = "00000" + eanCode;
	}
	// Check for 13 digits otherwise
	else if (eanCode.length != 13) {
		return false;
	}

	// Get the check number
	originalCheck = eanCode.substring(eanCode.length - 1);
	eanCode = eanCode.substring(0, eanCode.length - 1);

	// Add even numbers together
	even = Number(eanCode.charAt(1)) +
	       Number(eanCode.charAt(3)) +
	       Number(eanCode.charAt(5)) +
	       Number(eanCode.charAt(7)) +
	       Number(eanCode.charAt(9)) +
	       Number(eanCode.charAt(11));
	// Multiply this result by 3
	even *= 3;

	// Add odd numbers together
	odd = Number(eanCode.charAt(0)) +
	      Number(eanCode.charAt(2)) +
	      Number(eanCode.charAt(4)) +
	      Number(eanCode.charAt(6)) +
	      Number(eanCode.charAt(8)) +
	      Number(eanCode.charAt(10));

	// Add two totals together
	total = even + odd;

	// Calculate the checksum
    // Divide total by 10 and store the remainder
    checksum = total % 10;
    // If result is not 0 then take away 10
    if (checksum != 0) {
        checksum = 10 - checksum;
    }

	// Return the result
	if (checksum != originalCheck) {
		return false;
	}

    return true;
}

Note that this code can validate EAN-8 and EAN-13 barcodes.

,

No Comments

Onclick event is not fired on IE

I am pretty sure everybody knows that Internet Explorer has “a few” bugs… :roll:
You didn’t? 8-O Alright, better to stay on your little cloud and leave this blog right away!

For the others, I will talk about the JavaScript event onclick which is not fired when the following requirements are matched:

  • In a form;
  • There is only ONE input text element;
  • There is one button which has an onclick event assigned;
  • You press the ‘Enter’ button inside the input text element.

For a better understanding, let’s now take the following example:

<html>
    <head><title>Test</title><head>
    <body>
        <form>
            <input type="text" id="t1"/>
            <input type="submit" onclick="alert('onclick fired!'); return true;"/>
        </form>
    </body>
</html>

As you can see, there is nothing difficult in this code.
Well, that doesn’t mean Internet Explorer can handle it… :lol:

The bug occurs if you press the ‘Enter’ button inside the input text element using Internet Explorer. Indeed, the onclick event is not fired and the text ‘onclick fired!’ is not display to the user! However, it works perfectly fine on Firefox and Safari.

The funny thing is this code works on Internet Explorer if you add another input text, even if it is hidden!
Why? Don’t ask me! :-|

Anyway, the following example works on IE:

<html>
    <head><title>Test</title><head>
    <body>
        <form>
            <input type="text" id="t1"/>
            <input type="text" style="display:none"/>
            <input type="submit" onclick="alert('onclick fired!'); return true;"/>
        </form>
    </body>
</html>


Why are we assigning an onclick event to the submit button?
It could be for a lot of reasons, but the main one is probably to validate the form before submitting the data.

By the way, RichFaces is very often using this event on the submit buttons.
So remember to add a hidden input text to your form if you want to allow users to use the ‘Return’ key. :)

, , , , , ,

No Comments

Be careful of SKIP_COMMENTS

In the early days, we used to hide JavaScript code from old browsers that do not support JavaScript.
The way of doing this was to put a one-line HTML-style comment without the closing characters immediately after the opening <script> tag and put //--> at the end of the script.

For example:

<script type="text/javascript">
<!--
alert('Test');
//-->
</script>

However if you are using this trick with the initialization parameter facelets.SKIP_COMMENTS set to true, the code between <!-- and //--> won’t even be sent to the client!
It simply means that the code above won’t open an alert window because it has been skipped during the page rendering.

Here is what the client will receive:

<script type="text/javascript">
<!--
//-->
</script>


You have two solutions to avoid this situation:

  1. Set the SKIP_COMMENTS parameter to false (the default is true). This can’t really hurt, your page will just be heavier depending on how much HTML comments you put on your page;
  2. No need to hide the JavaScript code as all browsers are now supporting it and over 99.9% of users have it enabled – this is the solution I chose.

For information, below is the code to put in your web.xml file to set the SKIP_COMMENTS parameter to false:

<context-param>
    <param-name>facelets.SKIP_COMMENTS</param-name>
    <param-value>false</param-value>
</context-param>

, , ,

No Comments