Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 11-20 of 28 total

Using a mutiple collection select form helper with habtm or has many associations in Rails

// where user has and belongs to many roles

   1  
   2  # in your view
   3  <%= collection_select :user, :role_ids, Role.find(:all, :order => 'name ASC'), :id, :name, { :selected => @user.role_ids }, { :multiple => true, :name => 'user[role_ids][]' } -%>

PHP: Print List of States For A Select Field And Preselect A Value

Prints a list of US states for a <select> field and selects a predefined value. Use like this:
echo "<select name='billing_state'>";
state_list($_POST['billing_state']);
echo "</select>";

You can also convert this function to return a value instead of directly outputting

   1  
   2  function state_list($sel='') {
   3  	echo "<option value='AL'".($sel=='AL'?' selected':'').">Alabama</option>";
   4  	echo "<option value='AK'".($sel=='AK'?' selected':'').">Alaska</option>";
   5  	echo "<option value='AZ'".($sel=='AZ'?' selected':'').">Arizona</option>";
   6  	echo "<option value='AR'".($sel=='AR'?' selected':'').">Arkansas</option>";
   7  	echo "<option value='CA'".($sel=='CA'?' selected':'').">California</option>";
   8  	echo "<option value='CO'".($sel=='CO'?' selected':'').">Colorado</option>";
   9  	echo "<option value='CT'".($sel=='CT'?' selected':'').">Connecticut</option>";
  10  	echo "<option value='DE'".($sel=='DE'?' selected':'').">Delaware</option>";
  11  	echo "<option value='DC'".($sel=='DC'?' selected':'').">District of Columbia</option>";
  12  	echo "<option value='FL'".($sel=='FL'?' selected':'').">Florida</option>";
  13  	echo "<option value='GA'".($sel=='GA'?' selected':'').">Georgia</option>";
  14  	echo "<option value='GU'".($sel=='GU'?' selected':'').">Guam</option>";
  15  	echo "<option value='HI'".($sel=='HI'?' selected':'').">Hawaii</option>";
  16  	echo "<option value='ID'".($sel=='ID'?' selected':'').">Idaho</option>";
  17  	echo "<option value='IL'".($sel=='IL'?' selected':'').">Illinois</option>";
  18  	echo "<option value='IN'".($sel=='IN'?' selected':'').">Indiana</option>";
  19  	echo "<option value='IA'".($sel=='IA'?' selected':'').">Iowa</option>";
  20  	echo "<option value='KS'".($sel=='KS'?' selected':'').">Kansas</option>";
  21  	echo "<option value='KY'".($sel=='KY'?' selected':'').">Kentucky</option>";
  22  	echo "<option value='LA'".($sel=='LA'?' selected':'').">Louisiana</option>";
  23  	echo "<option value='ME'".($sel=='ME'?' selected':'').">Maine</option>";
  24  	echo "<option value='MD'".($sel=='MD'?' selected':'').">Maryland</option>";
  25  	echo "<option value='MA'".($sel=='MA'?' selected':'').">Massachusetts</option>";
  26  	echo "<option value='MI'".($sel=='MI'?' selected':'').">Michigan</option>";
  27  	echo "<option value='MN'".($sel=='MN'?' selected':'').">Minnesota</option>";
  28  	echo "<option value='MS'".($sel=='MS'?' selected':'').">Mississippi</option>";
  29  	echo "<option value='MO'".($sel=='MO'?' selected':'').">Missouri</option>";
  30  	echo "<option value='MT'".($sel=='MT'?' selected':'').">Montana</option>";
  31  	echo "<option value='NE'".($sel=='NE'?' selected':'').">Nebraska</option>";
  32  	echo "<option value='NV'".($sel=='NV'?' selected':'').">Nevada</option>";
  33  	echo "<option value='NH'".($sel=='NH'?' selected':'').">New Hampshire</option>";
  34  	echo "<option value='NJ'".($sel=='NJ'?' selected':'').">New Jersey</option>";
  35  	echo "<option value='NM'".($sel=='NM'?' selected':'').">New Mexico</option>";
  36  	echo "<option value='NY'".($sel=='NY'?' selected':'').">New York</option>";
  37  	echo "<option value='NC'".($sel=='NC'?' selected':'').">North Carolina</option>";
  38  	echo "<option value='ND'".($sel=='ND'?' selected':'').">North Dakota</option>";
  39  	echo "<option value='OH'".($sel=='OH'?' selected':'').">Ohio</option>";
  40  	echo "<option value='OK'".($sel=='OK'?' selected':'').">Oklahoma</option>";
  41  	echo "<option value='OR'".($sel=='OR'?' selected':'').">Oregon</option>";
  42  	echo "<option value='PW'".($sel=='PW'?' selected':'').">Palau</option>";
  43  	echo "<option value='PA'".($sel=='PA'?' selected':'').">Pennsylvania</option>";
  44  	echo "<option value='PR'".($sel=='PR'?' selected':'').">Puerto Rico</option>";
  45  	echo "<option value='RI'".($sel=='RI'?' selected':'').">Rhode Island</option>";
  46  	echo "<option value='SC'".($sel=='SC'?' selected':'').">South Carolina</option>";
  47  	echo "<option value='SD'".($sel=='SD'?' selected':'').">South Dakota</option>";
  48  	echo "<option value='TN'".($sel=='TN'?' selected':'').">Tennessee</option>";
  49  	echo "<option value='TX'".($sel=='TX'?' selected':'').">Texas</option>";
  50  	echo "<option value='UT'".($sel=='UT'?' selected':'').">Utah</option>";
  51  	echo "<option value='VT'".($sel=='VT'?' selected':'').">Vermont</option>";
  52  	echo "<option value='VI'".($sel=='VI'?' selected':'').">Virgin Islands</option>";
  53  	echo "<option value='VA'".($sel=='VA'?' selected':'').">Virginia</option>";
  54  	echo "<option value='WA'".($sel=='WA'?' selected':'').">Washington</option>";
  55  	echo "<option value='WV'".($sel=='WV'?' selected':'').">West Virginia</option>";
  56  	echo "<option value='WI'".($sel=='WI'?' selected':'').">Wisconsin</option>";
  57  	echo "<option value='WY'".($sel=='WY'?' selected':'').">Wyoming</option>";
  58  }

Dynamic Select Example

// Example of JavaScript to with with Select Options

   1  
   2  <html>
   3  <head>
   4  	<title>test</title>	
   5  </head>
   6  <body id="test" onload="">
   7  	<form>
   8  		<select id="lstStuff" multiple="multiple" onChange="lstStuff_OnChange()" size="6" style="width:200px;">
   9  			<option>item 1</option>
  10  			<option>item 2</option>
  11  			<option>item 3</option>
  12  			<option>item 4</option>
  13  			<option>item 5</option>
  14  			<option>item 6</option>			
  15  		</select>	
  16  		<br/>
  17  		<a href="javascript:selectAll('lstStuff', true);">all</a>
  18  		<a href="javascript:selectAll('lstStuff', false);">none</a>
  19  		<p/>
  20  		<select id="lstOtherStuff" multiple="multiple" size="6" style="width:200px;">
  21  		</select>
  22  		<br/>
  23  		<a href="javascript:selectAll('lstOtherStuff', true);">all</a>
  24  		<a href="javascript:selectAll('lstOtherStuff', false);">none</a>
  25  	</form>
  26  	<script type="text/javascript" charset="utf-8">
  27  		var otherStuff = {
  28  			"item 1" : [ "subitem 1.1", "subitem 1.2", "subitem 1.3", "subitem 1.4" ],
  29  			"item 2" : [ "subitem 2.1", "subitem 2.2" ],
  30  			"item 4" : [ "subitem 4" ],
  31  			"item 6" : [ "subitem 6.1", "subitem 6.2" ]
  32  		};
  33  	</script>
  34  	<script type="text/javascript" charset="utf-8">
  35  		function selectAll(listName, selected) {
  36  			var listBox = document.getElementById(listName);
  37  			for(i=0; i<listBox.length; i++) {
  38  				listBox.options[i].selected=selected;
  39  			}
  40  			if( listBox.onchange ) {
  41  				listBox.onchange();
  42  			}
  43  		}
  44  		function lstStuff_OnChange() {
  45  			var listBox = document.getElementById("lstStuff");
  46  			var subListBox = document.getElementById("lstOtherStuff");
  47  			subListBox.options.length=0;
  48  			for(i=0; i<listBox.length; i++) {
  49  				if( listBox.options[i].selected ) {
  50  					var key = listBox.options[i].text;
  51  					if(otherStuff[key]) {
  52  						for(j=0; j<otherStuff[key].length; j++) {
  53  							subListBox.options.add(new Option(otherStuff[key][j],otherStuff[key][j]));
  54  						}
  55  					}
  56  				}
  57  			}
  58  		}
  59  	</script>
  60  </body>
  61  </html>
  62  

PRNG In SQL Select

Simple example of a PRNG (pseudo-random number generator) written into a SQL statement

Example is in T-SQL, but it ports well

Actual application should use either a better random algorithm, or the output be used with randomized seeds. This is definitely not cryptographically secure. It's very handy if you need a simple random number with your recordset though.

   1  
   2  -- Setup some vars we'll need
   3  DECLARE @prng TABLE (seed BIGINT, rnum nchar(10))
   4  DECLARE @seeds TABLE (seed BIGINT)
   5  DECLARE @seed BIGINT
   6  DECLARE @C1 BIGINT, @C2 BIGINT, @C3 BIGINT
   7  SET @seed = 0
   8  SET @C1 = 1664525
   9  SET @C2 = 4294967296
  10  SET @C3 = 1013904223
  11  
  12  -- Create a seed table so we can have some data to use
  13  WHILE @seed < 10
  14  BEGIN
  15      INSERT INTO @seeds (seed) VALUES (@seed)
  16      SET @seed = @seed + 1
  17  END
  18  
  19  -- Create our PRNG (inserts into table for illustrative purposes)
  20  -- prng(seed) ::= ((((C1 * seed) % C2) + C3) % C2) / C2
  21  -- Then convert prng(seed) into a string
  22  -- of 10 chars, 8 of which are decimal places
  23  INSERT INTO @prng
  24  SELECT
  25      seed,
  26      REPLACE(
  27          STR(
  28              ( CAST((((@C1*seed)%@C2)+@C3)%@C2 AS FLOAT) )
  29              / ( CAST(@C2 AS FLOAT)),
  30              10, 8
  31          ),
  32          ' ', '0') AS rnum
  33  FROM @seeds
  34  
  35  -- Let's take a look at what we created
  36  SELECT * FROM @prng

Selezione di elementi JS

   1  
   2  <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
   3          "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
   4  <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
   5  <head>
   6    <title>Prova di selezione rettangolo</title>
   7    <script src="http://www.prototypejs.org/javascripts/prototype.js" type="text/javascript"></script>
   8    
   9    <script>
  10    
  11  	Event.observe(window, 'load',function() {
  12  	
  13  		Event.observe(document, 'mousedown', MyDragger.OnMouseDown);
  14  		Event.observe(document, 'mouseup', MyDragger.OnMouseUp);
  15  		Event.observe(document, 'mousemove', MyDragger.OnMouseMove);
  16  	});
  17    
  18  		// cevrond 2007.05.11
  19    
  20    var MyDragger = window.MyDragger || {};
  21    
  22    MyDragger.PointClick = { x: -1, y: -1 };
  23    MyDragger.Status = -1; // -1: not dragging, 0: clicked, 1: dragging
  24    MyDragger.Targets = [];
  25  
  26    MyDragger.OnMouseDown = function(e) {
  27  
  28  		MyDragger.Log('mouse', 'mousedown');
  29  
  30  		MyDragger.PointClick.x = Event.pointerX(e);
  31  		MyDragger.PointClick.y = Event.pointerY(e);
  32  
  33  		MyDragger.SetBox(MyDragger.PointClick.x, MyDragger.PointClick.y, -1, -1);
  34  		MyDragger.Status = 0;
  35  		
  36  		var els = $$('div.pippo');
  37  		for (var i = 0, m = els.length ; i < m; i++) {
  38  
  39  			var el = els[i];
  40  
  41  			MyDragger.ElUnselect(el);
  42  
  43  			var xy = Position.cumulativeOffset(el);
  44  			var wh = el.getDimensions();
  45  			
  46  			var t = { el: el, l: xy[0], t: xy[1], r: xy[0] + wh.width, b: xy[1] + wh.height, hl: false};
  47  
  48  			MyDragger.Targets[ MyDragger.Targets.length ] = t;
  49  		}
  50  
  51  		return false;
  52  	}
  53  
  54    MyDragger.OnMouseUp = function(e) {
  55    
  56  		MyDragger.Log('mouse', 'mouseup');
  57  
  58  		MyDragger.Status = -1;
  59  		MyDragger.Targets = [];
  60  
  61  		return false;
  62  	}
  63  
  64    MyDragger.OnMouseMove = function(e) {
  65    
  66  		var x = Event.pointerX(e);
  67  		var y = Event.pointerY(e);
  68  
  69  		MyDragger.Log('pointer', "X1: " + MyDragger.PointClick.x + " -- X2: " + x + " -- Y1: " + MyDragger.PointClick.y + " -- Y2: " + y);
  70  
  71  		var cw = Math.abs(MyDragger.PointClick.x - x);
  72  		var ch = Math.abs(MyDragger.PointClick.y - y);
  73  
  74  			// evita di cominciare la selezione se non si è mosso di almeno 2px
  75  
  76  		if (MyDragger.Status === 0 && (cw > 2 || ch > 2))
  77  			MyDragger.Status = 1;
  78  
  79  		if (MyDragger.Status === 1) {
  80  	
  81  			var cl = Math.min(MyDragger.PointClick.x, x);
  82  			var ct = Math.min(MyDragger.PointClick.y, y);
  83  
  84  			MyDragger.SetBox(ct, cl, cw, ch);
  85  
  86  			var cb = ct + ch;
  87  			var cr = cl + cw;
  88  
  89  			for (var i = 0, m = MyDragger.Targets.length; i < m; i++) {
  90  			
  91  				var d = MyDragger.Targets[i];
  92  			
  93  				((cl > d.r || cr < d.l || ct > d.b || cb < d.t) ? MyDragger.ElUnselect : MyDragger.ElSelect)(d.el);
  94  			}
  95  		}
  96  		
  97  		return false;
  98  	}
  99  
 100  		// interazione con gli elementi
 101  
 102  	MyDragger.ElSelect = function(el) {
 103  
 104  		el.setStyle({backgroundColor:'red'});
 105  	}
 106  
 107  	MyDragger.ElUnselect = function(el) {
 108  
 109  		el.setStyle({backgroundColor:'transparent'});
 110  	}
 111  	
 112  		// interazione col box di selezione
 113  
 114  	MyDragger.SetBox = function(t, l, w, h) {
 115  
 116  		var box = $('box');
 117  		
 118  		if (w === -1 || h === -1)
 119  			box.setStyle({ display: 'none' });
 120  		else
 121  		box.setStyle({
 122  			display: '',
 123  			top: t + 'px',
 124  			left: l + 'px',
 125  			width: w + 'px',
 126  			height: h + 'px'
 127  		});
 128  	}
 129  
 130  		// per un po' di logging ...
 131  
 132    MyDragger.Log = function(where, what) {
 133    
 134  		$(where).innerHTML = what;
 135  	}
 136  
 137    </script>
 138  </head>
 139  <body>
 140  <div id="debug_container" style="border: 1px red solid">
 141  	<div id="mouse"></div>
 142  	<div id="pointer"></div>
 143  	<div id="pippoc"></div>
 144  	<div id="rectc"></div>
 145  </div>
 146  
 147  <div id="box" style="border: 1px green solid; position: absolute;z-Index: 1000"></div>
 148  
 149  <div id="pippo" class="pippo" style="position:absolute;left:200px;top:200px;width:100px;height:100px;border: 2px blue solid" onclick="pippoClick(this)"></div>
 150  <div id="pippo2" class="pippo" style="position:absolute;left:300px;top:200px;width:100px;height:100px;border: 2px blue solid" onclick="pippoClick(this)"></div>
 151  <div id="pippo3" class="pippo" style="position:absolute;left:400px;top:200px;width:100px;height:100px;border: 2px blue solid" onclick="pippoClick(this)"></div>
 152  
 153  </body>
 154  </html>

Enumerable#select_with_index

   1  
   2  
   3  
   4  module Enumerable
   5  
   6     def select_with_index
   7        index = -1
   8        (block_given? && self.class == Range || self.class == Array)  ?  select { |x| index += 1; yield(x, index) }  :  self
   9     end
  10  
  11     def select_with_index_blk(&block)
  12        index = -1
  13        (block && self.class == Range || self.class == Array)  ?  select { |x| index += 1; block.call(x, index) }  :  self
  14     end
  15  
  16  end
  17  
  18  
  19  p ('a'..'n').select_with_index { |x, i| x if i % 2 == 0 }
  20  p ('a'..'n').select_with_index_blk { |x, i| x if i % 2 == 0 }
  21  
  22  
  23  require 'benchmark' 
  24  
  25  num = 1000000
  26  
  27  Benchmark.bm(8) do |t| 
  28  
  29    t.report('yield:') do 
  30      (0..num).select_with_index { |x, i| x } 
  31      #(0..num).select_with_index { |x, i| x if i % 2 == 0 } 
  32   end 
  33  
  34   t.report('block:') do
  35      (0..num).select_with_index_blk { |x, i| x } 
  36      #(0..num).select_with_index_blk { |x, i| x if i % 2 == 0 } 
  37   end 
  38  
  39  end 
  40  
  41  

Select random row, SQL Server

// select a random row in SQL Server, apparently. Untested.

   1  
   2  SELECT TOP 1 column FROM table
   3  ORDER BY NEWID()

Javascript QuickSelect (Coordinated Textbox And ListBox)

In HTML, say you have a select element with all the states.
Unfortunately typing in this select box only works with the first letter.
So if you type P then A you don't select pennsylvania.
What I commonly do in this situation is to have what I call a quickselect textbox on the page as well.
This is a textbox and listbox that are coordinated.

   1  
   2  // in your onload event handler you need this
   3  
   4  // hookup event handlers and control references
   5  var objElement = document.getElementById('cboState');
   6  if ( objElement )
   7     {
   8     objElement.onchange = QuickSelect_Change;
   9     objElement.textbox = document.getElementById('txtState');
  10     if ( objElement.textbox )
  11        {
  12        objElement.textbox.onchange = QuickSelect_TextChange;
  13        objElement.textbox.onblur = QuickSelect_TextChange;
  14        objElement.textbox.onkeypress = QuickSelect_KeyPress;
  15        objElement.textbox.listbox = objElement;
  16        }
  17     }       
  18  
  19  // and now the functions
  20  
  21  // ----------------------------------------------------------------------------
  22  // QuickSelect_KeyPress
  23  //
  24  // Description : event handler for quick select textbox's key press event
  25  //    selects the appropriate item in the associated listbox control
  26  //
  27  // Arguments : none
  28  //
  29  // Dependencies : 
  30  //
  31  // History :
  32  // 2006.09.20 - WSR : created
  33  //
  34  function QuickSelect_KeyPress( e )
  35     {
  36  
  37  
  38     var strCompare = '';
  39     var numEntryLen;
  40     var strEntry;
  41     var objSelect = this.listbox;
  42     var numOptions = objSelect.options.length;
  43  
  44     var numCharCode;
  45     var elTarget;
  46  
  47     // get event if not passed
  48     if (!e) var e = window.event;
  49  
  50     // get character code of key pressed
  51     if (e.keyCode) numCharCode = e.keyCode;
  52     else if (e.which) numCharCode = e.which;
  53  
  54     // get target
  55     if (e.target) elTarget = e.target;
  56     else if (e.srcElement) elTarget = e.srcElement;
  57                                                
  58     // if form input field & it is a printable character
  59     if ( elTarget.nodeName.toUpperCase() == 'INPUT' && numCharCode >= 32 && numCharCode <= 126 )
  60        {
  61  
  62        strEntry = this.value + String.fromCharCode(numCharCode);
  63        numEntryLen = strEntry.length;
  64  
  65        // cycle through options
  66        for (var i = 0; i < numOptions; i++)
  67           {
  68  
  69           // get compare string from value same length as entered string
  70           strCompare = objSelect.options[i].value.substring(0, numEntryLen);
  71  
  72           // if value matches what is entered
  73           if (strEntry == strCompare)
  74              {
  75  
  76              // select this option
  77              objSelect.options[i].selected = true;
  78  
  79              // end loop
  80              break;
  81  
  82              }
  83  
  84           }
  85  
  86        // I usually add an error class when input is required and not filled in
  87        // this removes the class so the input is no longer marked as invalid
  88        // commented out as it isn't necessary for general purpose
  89        // RemoveClassName( this, 'error' );
  90  
  91        }
  92  
  93     }
  94  //
  95  // QuickSelect_KeyPress
  96  // ----------------------------------------------------------------------------
  97  
  98  
  99  // ----------------------------------------------------------------------------
 100  // QuickSelect_TextChange
 101  //
 102  // Description : event handler for quick select textbox's change & onblur events
 103  //    makes sure item in textbox is a value from list
 104  //
 105  // Arguments : none
 106  //
 107  // Dependencies : none
 108  //
 109  // History :
 110  // 2006.08.09 - WSR : created
 111  //
 112  function QuickSelect_TextChange()
 113     {
 114  
 115     var strCompare = '';
 116     var numEntryLen = this.value.length;
 117     var strEntry = this.value;
 118     var objSelect = this.listbox;
 119     var numOptions = objSelect.options.length;
 120  
 121     // cycle through options
 122     for (var i = 0; i < numOptions; i++)
 123        {
 124  
 125        // get compare string from value same length as entered string
 126        strCompare = objSelect.options[i].value.substring(0, numEntryLen);
 127  
 128        // if value matches what is entered
 129        if (strEntry == strCompare)
 130           {
 131  
 132           // select this option
 133           objSelect.options[i].selected = true;
 134  
 135           // end loop
 136           break;
 137  
 138           }
 139  
 140        }
 141  
 142     // copy code to textbox
 143     this.value = this.listbox.options[this.listbox.selectedIndex].value;
 144  
 145     // I usually add an error class when input is required and not filled in
 146     // this removes the class so the input is no longer marked as invalid
 147     // commented out as it isn't necessary for general purpose
 148     // RemoveClassName( this, 'error' );
 149  
 150     }
 151  //
 152  // QuickSelect_TextChange
 153  // ----------------------------------------------------------------------------
 154  
 155  
 156  // ----------------------------------------------------------------------------
 157  // QuickSelect_Change
 158  //
 159  // Description : event handler for quick select list box's change event
 160  //    updates the textbox with the selected value
 161  //
 162  // Arguments: none
 163  //
 164  // Dependencies :
 165  //
 166  // History :
 167  // 2006.08.09 - WSR : created
 168  //
 169  function QuickSelect_Change()
 170     {
 171  
 172     // copy code to textbox
 173     this.textbox.value = this.options[this.selectedIndex].value;
 174  
 175     }	
 176  //
 177  // QuickSelect_Change
 178  // ----------------------------------------------------------------------------
 179    


Dropdown select list

   1  
   2  /**
   3   * generates html select dropdown list with options
   4   * if values is two dimensional then adds optgroup too
   5   * 
   6   * @param 	string	$name			selectbox name and id
   7   * @param 	array		$values		options
   8   * @param 	mixed		$selected	selected option
   9   * @param 	array		$attributes additonal attributes
  10   *