Click here to Skip to main content
15,886,030 members
Articles / Programming Languages / Javascript
Tip/Trick

Jquery Plugin to Enable an Element with a Simple Expression

Rate me:
Please Sign up or sign in to vote.
5.00/5 (1 vote)
19 Oct 2017CPOL2 min read 6.4K   2  
Enable a button with a simple expression in its attribute , basing on the status of the referenced elements

Introduction

I did it on the job, for my own need and I am just sharing it, should someone find it useful.

Background

Of course, there are plenty of plugins doing web controls validation. This plug in doesn't validate, but just enables or disables a control reading one of its attributes, and basing on the status of the referenced elements.

Using the Code

Image 1

 

This is an example:

HTML
<input type='button' data-enabled-if='firstname && lastname' value='Submit' />

It just will check if elements having IDs firstname and lastname have both contents. In the attached example, they are two textboxes.

Of course, you can combine elements ID in a logical expression, so you could write:

HTML
<input type='button' data-enabled-if='firstname && lastname && (privacy||payment ) ' value='Submit' />

In this case, privacy is a checkbox, and payment is a name of a radiobuttons group. One of them must be checked for the button to be enabled (provided that firstname and lastname are not empty).

The below statement is also accepted:

HTML
<input type='button' data-enabled-if='firstname && lastname && ! privacy' value='Submit' />

where the button is enabled only if firstname and lastname have content, and privacy is NOT checked.

Points of Interest

The values in the data-enabled-if attribute are searched mainly as ID. If a value is not found as an ID, it's searched as a name for radiobuttons group. Find below the behaviour for different type of elements.

TextBox Return true if it has content
TextArea Return true if it has content
CheckBox Return true if it is checked
Select Return true if an item is selected
RadioButton (name) Return true if an item is checked

Activate the plug in by:

JavaScript
$(document).ready(function(){ $(".container").enabledIf();  });

plug in code follows:

JavaScript
(function ($) {
    $.fn.enabledIf = function () {
          this.each(function () {
              $("[data-enabled-if]").each(function () {
                  // set an id if missing
                  if ($(this).attr("id")==undefined)
                      {$(this).attr("id","obj-"+new Date().getTime());}
                  //get the attribute value
                  var att = ($(this).attr("data-enabled-if"));
                  //remove logical expression characters
                  var mod = att.replace(new RegExp("[&|()!]", "g"), ' ');
                  //split by space and remove empty items
                  var r = mod.split(' ');
                  r = r.filter(function (entry) { return entry.trim() != ''; });
                  //for any word found in array r
                  for (var i = 0; i < r.length; i++) {
                      //if it is an ID, take the corresponding element
                      var $elements = [];
                      if ($("#" + r[i]).length > 0)
                           $elements.push($("#" + r[i]));
                      else {
                         //else it's a name for radiobuttons, so take all the radios
                         $("input:radio[name='" + r[i] + "']").each(function () {
                                $elements.push($(this));
                               });
                            }
                           //for any element
                           for (var k = 0; k < $elements.length; k++) {
                              var $element = $($elements[k]);
                              //add an attribute data-enabling with value of the object to be enabled
                              $element.attr("data-enabling", $(this).attr("id"));
                              //add an attribute data-enable-group with value= logical expression
                              $element.attr("data-enable-group", att);
                              //for any change on this element:
                              $element.on('input propertychange paste change', function () {
                                 var logicalExpr = $(this).attr("data-enable-group");
                                 //check status of any element involved in the expression,
                                 //replace them with true/false
                                 //eval the expression
                                 for (var k = 0; k < r.length; k++) {
                                       var v = isElementVal(r[k]);
                                       var reg = new RegExp(r[k], "g");
                                       logicalExpr = logicalExpr.replace(reg, v);
                                 }
                                 if (eval(logicalExpr) == true) {
                                    $("#" + $(this).attr("data-enabling")).removeAttr("disabled");
                                 }
                                 else {
                                    $("#" + $(this).attr("data-enabling")).attr
                                                              ("disabled", "disabled");
                                 }
                           });
                           $element.change();
                      }
                 }
           });
   });
   return this;
};
function isElementVal(id) {
    var el = $("#" + id);
    //if id doesn't exist, assume it's a 'name' for a radiobuttons group
    if (el.length == 0)
         return $("input:radio[name='" + id + "']").is(":checked");

    //if it's a checkbox, return if checked
    if ($(el).is("input[type=checkbox]")) {
         return $(el).prop("checked");
         }
         else{
         //else return if it has any content
         return $.trim($("#" + id).val()) != "";
         }
}
}(jQuery));

As a limitation, please note that an element can be used only once for the time being. That is, if an element ID is in a data-enabled-if attribute, it cannot also be in another.

Author

Max Aronica is a senior .NET full-stack Developer working as external consultant for enterprise customers in Rome, Italy.

History

  • 19/10/2017: First release

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Italy Italy
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
-- There are no messages in this forum --