Using Javascript can be an awesome way to have user’s input alter the page content and style. For example a link could run a Javascript function to alter it’s class (with class styling via CSS):
<script type=”text/javascript” >
function changeMe(){
document.getElementById(“button”).setAttribute(“class”, “activated”);
}
</script>
<a href=”javascript:changeMe()” alt=”Change the class” id=”button” class=”notActivated” >Change the class</a>
This is all very well and said for Firefox, Safari or Opera users, but take a look on Internet Explorer 7 and you will have nothing happen! Luckily, this is very simple to fix. By adding a backup line of code into the Javascript function you can ensure IE knows what should happen:
document.getElementById(“button”).className = “activated”;
Click me to see a live example.
Give it a go and if your interested in improving your Google/Search results – give us a email
So in a recent web project I decided to incorporate some fancy Javascript form-verification code. Thinking it would be a breeze, I started with a link to submit the form and run the Javascript function:
<a href=”javascript:submitForm()”>Send form</a>
After I made the Javascript function work I then realised I had no idea how tell the page to submit the form. I discussed this problem with a colleague and he told me I was doing it all wrong. Best practice is to have a normal submit button and link the Javascript function at the bottom of the form. In my case I was using PHP which detected if the form was ready to send an email or not, so the form’s action was left empty (action=”").
In the Javascript I referenced the form with:
var f = document.getElementById(“contact-form”);
f.onsubmit = submitForm;
var f = document.getElementById(“contact-form”);
f.onsubmit = submitForm;
This code is vital to make this work as it links the HTML form and the Javascript function together. Once the submit button is pressed, the Javascript function runs (I called it submitForm) and if it encounters and error it returns false. This tells the HTML that the submission was unsuccessful.
Long story short, Javascript can be run between clicking Submit and the actual submit process to decide if the form is valid. From there you can run the appropriate error message or proceed to the submit script. Still don’t get what I mean? Check out a live test version at: http://www.jamesbarnsley.co.nz/mbv/dev.