Tuesday, August 21, 2012

forms – Javascript to validate element values and checkboxes

i want to use js to check a form in the case that none of my checkboxes are checked and the input field hasn\’t been filled. When this is the case, the user should get a message that tells them to make at least one choice or formulate their own.


The form elements…



<input type=\"checkbox\" name=\"checkboxA\" id=\"checkboxA\" value=\"X\" />
<input type=\"checkbox\" name=\"checkboxB\" id=\"checkboxB\" value=\"Y\" />
<input type=\"checkbox\" name=\"checkboxC\" id=\"checkboxC\" value=\"Z\" />

<input type=\"text\" id=\"Text\" class=\"textfield\" value=\"please enter text.\" maxlength=\"100\" size=\"40\" onblur=\"if (this.value == \'\') {this.value = \'please enter text\';}\" onfocus=\"if (this.value == \'please enter text\') {this.value = \'\';}\" />


…are checked by this js funtion when the POST method is performed:



function checkFormElement() {
if ((document.getElementById(\"text\").value == \"please enter text.\")
&& (document.getElementById(\"checkboxA\").checked == false)
&& (document.getElementById(\"checkboxB\").checked == false)
&& (document.getElementById(\"checkboxC\").checked == false)){
alert(\"Please choose out of X Y Z or formulate your own choice .\");
document.getElementById(\"checkboxA\").focus();
return false;
}
return true;


}


I guess using Jquery should be much easier but i still love to know how to solve this in pure js.


Thanks in advance.






Rating: 5 out of 5 based on 3 ratings



The post forms – Javascript to validate element values and checkboxes appeared first on Javascript ASK.






via Javascript ASK http://javascriptask.phpfogapp.com/forms-javascript-to-validate-element-values-and-checkboxes.html

No comments:

Post a Comment