The code below will first try to use the new dataset property. If that fails it will fallback to trying the getAttribute() method. This ensures that all browsers will behave the same regardless of their support for HTML5. And for good measure there is another fallback to a very generic message.
To take this a step further, you could use a dynamic programming language like ColdFusion to dynamically inject the message. You could even have it display a language-specific message (i.e., English, Spanish, etc.).
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<html> | |
<head> | |
<title>Data Error Message Sandbox</title> | |
<script type="text/javascript"> | |
function checkForm() { | |
var myformelement = document.getElementById('myformelement'); | |
var usermessage = document.getElementById('usermessage'); | |
if (myformelement.value == "") { | |
try { | |
alert(myformelement.dataset.errorMessage); | |
usermessage.innerHTML = "dataset"; | |
} | |
catch(err) { | |
try { | |
alert(myformelement.getAttribute('data-error-message')); | |
usermessage.innerHTML = "getAttribute"; | |
} | |
catch(err) { | |
alert("Invalid data"); | |
usermessage.innerHTML = "basicAlert"; | |
} | |
} | |
return false; | |
} | |
else { | |
return true; | |
} | |
} | |
</script> | |
</head> | |
<body> | |
<div id="usermessage"></div> | |
<form id="myform" name="myform" method="post" action="" onsubmit="return checkForm();"> | |
<label for="myformelement">My Form Element</label> | |
<input type="text" id="myformelement" name="myformelement" value="" data-error-message="Invaid data in 'My Form Element'" /> | |
<input type="submit" id="btnsubmit" name="btnsubmit" value="Submit" /> | |
</form> | |
</body> | |
</html> |
This comment has been removed by a blog administrator.
ReplyDelete