After going through a tutorial on how make jQuery plugins, I decided to give it a shot and make a form validation plugin. I’ve so far managed to achieve 90% of what I was hoping for and the only thing remaining is making the form to return false if there are empty fields found.
I’ve put my whole code at jsfiddle, but it doesn’t seem to be working. Perhaps because I need to include my plugin file instead of pasting it in the script section. But I’m sharing it just in case you need to look at the whole code.
PLUGIN WORKFLOW
(function(jQuery) {
window.cnt = 0;
jQuery.fn.border = function() {
this.each(function() {
var ele = jQuery(this);
var cur_val, ele_name;
if(// element is input, select, or textarea)
{
cur_val = ele.val();
}
else if(// element is radio)
{
ele_name = ele.attr('name');
cur_val = $('input:radio[name="'+ele_name+'"]:checked').val();
}
else if(// element is checkbox)
{
ele_name = ele.attr('name');
cur_val = $('input:checkbox[name="'+ele_name+'"]:checked').val();
}
if(! cur_val) // need to do something here to prevent form submission
{
cnt++;
if(// input, textarea, select element)
{
ele.addClass('border');
}
else if(// radio or checkbox element)
{
ele.parent().addClass('border');
}
}
else // need to do something here to make the form submission happen
{
if(// input, select, textarea)
{
ele.removeClass('border');
}
else if(radio or checkbox)
{
ele.parent().removeClass('border');
}
}
});
return this;
};
})(jQuery);// JavaScript Document
WHAT I TRIED
<script type="text/javascript">
$(function(){
$('form').submit(function(){
$('.required').border();
if(window.cnt > 0)
{
return false;
}
else
{
return true;
}
});
});
</script>
I created a global variable cnt and tried using it inside the form submission function. It worked when there were empty elements, but it returned false even after all elements where filled up. After alerting the value of cnt, I found out that on each button click the value of cnt kept appending from its previous values and so cnt > 0 always returned true.
Thus, I’m trying to find a way to return false from within the plugin function itself so that I won’t have to add the if-else condition after calling the plugin function.
In a nutshell what I’m trying to achieve is
$(function(){
$('form').submit(function(){
$('.required').border(); // this line should take care of returning true or false for the submit function
});
});
Thus, the user should just call $('.required').border(); and it should take care of the rest.
See the way I’m using the
validvariable in the code below, instead ofwindow.cnt.