Thursday, December 6, 2007

Javascript Substring() Function Cross-Browser Differences

I found something interesting while working on some Javascript form submission code. The problem was that the form was only submitting in IE and not in FireFox. After some troubleshooting I was able to determine that the Substring function is different between the two browsers. Here is an example if you want to give it a try.


<script language='javascript' type='text/javascript'>

function controlSubmit(obj,act) {
   obj.action = act;
   alert(obj.action.substring(0,13));
   if (obj.action.substring(0,13) == 'action.cfm') obj.submit();
}
</script>
<form>
   <input type="button" value="one" onclick="controlSubmit(this.form,'admin.cfm');">
   <input type="button" value="two" onclick="controlSubmit(this.form,'action.cfm');">
</form>


You will notice that the first button will only display an alert on both browsers and the second button will display an alert on both browsers, but it will also do a form submit only on IE. Moral of the story, be careful when using the Substring() javascript function when aiming for multiple browser support.