andrew4582

Create Select Options jQuery plug-in

Sep 27th, 2013
207
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1.     /*
  2.    
  3.     jQuery plug-in to create select options without to create manually html every time
  4.    
  5.     * Copyright (c) 2013 Andrew Hodgson
  6.  
  7.     //Example:
  8.     jQuery(function($){
  9.        
  10.         //create option's html
  11.         var optionHtml= $.Options.create("New York","NY");
  12.      
  13.         $("#stateselect").append(optionHtml);
  14.      
  15.         //add select's option directly
  16.         $("#stateselect")
  17.         .addOption("Texas","TX")
  18.         .addOption("Maine","MA");
  19.        
  20.         //add number options
  21.         for(var i = 1;i<= 10;i++)
  22.             $("#inputCntSel").addOption(i);
  23.        
  24.     });
  25.  */
  26.     (function($) {
  27.         $.Options = {
  28.             create: function(text,value){
  29.                 const optionfmt = "<option>[TEXT]</option>";
  30.                 const optionvalfmt = "<option value='[VALUE]'>[TEXT]</option>";
  31.                
  32.                 var formatted = "";    
  33.                 if(value == null)
  34.                     formatted = optionfmt.replace("[TEXT]", text);
  35.                 else
  36.                     formatted = optionvalfmt.replace("[TEXT]", text).replace("[VALUE]",value);
  37.                
  38.                 return formatted;
  39.             }
  40.         };
  41.         $.fn.addOption = function(text,value) {
  42.             var select=$(this);
  43.            
  44.             var optionHtml= $.Options.create(text,value);
  45.             return select.append(optionHtml);
  46.         };
  47.     })(jQuery);
Advertisement
Add Comment
Please, Sign In to add comment