Account services

Bad habits 7: Non-accessible javascript

The bad habit presented here is an example of what to avoid if you want to code to WAI-AA accessibility guidelines. So, what is wrong with this code?

  <script language="JavaScript">

     function submitForm(mode){
        if (mode == "delete"){
           var b = confirm("This value will be deleted! Click OK, if you want to continue. Otherwise click Cancel.");
           if (b==false) return;
        }

        document.forms["form1"].elements["mode"].value = mode;
        document.forms["form1"].submit();
     }
  </script>

  <form name="form1" method="post" action="m_attr_field.jsp">
    <input type="button" value="Save" onclick="submitForm('edit')"/>
    <input type="button" value="Delete" onclick="submitForm('delete')"/>

  </form>
  

The problems

  1. onclick only works if the user has a mouse. You would also need an onkeypress, but this is also bad practice. For scripts, specify logical event handlers rather than device-dependent event handlers.
  2. Doesn't work if javascript is turned off.

The replacement

  <script type="text/javascript">
  // <![CDATA[
     function submitForm(){
        if (mode == "Delete"){
           var b = confirm("This value will be deleted! Click OK, if you want to continue. Otherwise click Cancel.");
           if (b==false) return false;
        }
     }
  // ]]>
  </script>

  <form onsubmit="submitForm()" method="post" action="m_attr_field.jsp">
    <input type="submit" name="mode" value="Save"/>
    <input type="submit" name="mode" value="Delete"/>
  </form>
  

This works without javascript, except you will not get the warning if you click on delete. If the warning is important then it should be implemented on the server side. You also don't need a mouse, and you can tab your way to the buttons. Note that since the submit buttons have a name attribute, the value of the button will be sent as a variable to the server. That is how the server side script can distinguish between the two buttons.

Note that there's a problem in the case of multilinguality. Then the words "Save" and "Delete" will be different. The way to overcome this is to have different values in the name attribute of the buttons and then check which one is set to something in submitForm and on the server side.