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 1-10 of 15 total  RSS 

'Delete a Twitter entry' dissected

The following code was copied from my Twitter home page, it shows how to delete a twitter entry on the server.

raw HTML code with embedded JavaScript code.
   1  
   2  
   3  <a href="/status/destroy/719423092" onclick="if (confirm('Sure you want to delete this update? There is NO undo!')) 
   4  {var f = document.createElement('form'); f.style.display = 'none'; this.parentNode.appendChild(f); f.method = 
   5  'POST'; f.action = this.href;var m = document.createElement('input'); m.setAttribute('type', 'hidden'); 
   6  m.setAttribute('name', '_method'); m.setAttribute('value', 'delete'); f.appendChild(m);var s = 
   7  document.createElement('input'); s.setAttribute('type', 'hidden'); s.setAttribute('name', 'authenticity_token'); 
   8  s.setAttribute('value', 'd0057265c3784d2a6dc6cdb2c26083f638152151'); f.appendChild(s);f.submit(); };return false;" 
   9  title="Delete this update?">


same code as above but with comments.
   1  
   2  <a href="/status/destroy/719423092" onclick="
   3  
   4                       // if the user clicks the 'OK' button the confirm function will return true
   5  if (confirm('Sure you want to delete this update? There is NO undo!')) { 
   6  
   7    // -- dhtml: creating html elements on-the-fly -------------------------------
   8    var f = document.createElement('form'); // create the dhtml 'form' (<form/>) element
   9    f.style.display = 'none';               // hide the form
  10    this.parentNode.appendChild(f);         // append the form element to the parent of the current node (<a/>)
  11    f.method = 'POST';                      // add the method to the form
  12    f.action = this.href;                   // add the action using the href of the current node (<a/>)
  13      
  14    var m = document.createElement('input');   // create the input (<input/>) 'element' 
  15    m.setAttribute('type', 'hidden');          // set the input type to 'hidden'
  16    m.setAttribute('name', '_method');         // set the input name to '_method'
  17    m.setAttribute('value', 'delete');         // set the input value to 'delete'
  18    f.appendChild(m);                          // append the input element to the form element
  19    
  20    var s = document.createElement('input');   // create another input element
  21    s.setAttribute('type', 'hidden');          // set the type to 'hidden'
  22    s.setAttribute('name', 'authenticity_token'); // set the name to 'authenticity_token'
  23    
  24                                       // set the input element's value using a unique id.
  25    s.setAttribute('value', 'd0057265c3784d2a6dc6cdb2c26083f638152151'); 
  26    
  27    f.appendChild(s);                  // apend the input element to the form element
  28    // -- end of dhtml: creating html elements on-the-fly -------------------------------
  29    
  30    f.submit(); // post the form data back to the server to delete the record, 
  31                // just as if the user had pressed the submit button.
  32  };
  33  
  34    return false; // returning false cancels the default <a href="..."> request. 
  35                   // However if JavaScript had been disabled for some reason the 
  36                   // <a href="..."> would have acted normally, meaning the record 
  37                   // would have been deleted from following the URL request directly.
  38   "

Note: Twitter needs JavaScript for the web page to work properly, I've tried and it is not possible to delete a record without JavaScript. The authenticity_token has been altered by me to prevent any malicious activity on my Twitter account.

Capturing the value from an HTML text box - Ajax style

This extract of JavaScript code illustrates how the value of a text box on an HTML form could be saved efficiently when used with AJAX.
   1  
   2  <input type="text" name="proj1" id="proj1" value="Car_log" 
   3    onkeyup="timed_updateSummaryCRecord(event.keyCode, '1','project', this.value)" />

The onkeyup event retrieves the user input as soon as the key is pressed, then the event.keyCode is validated to ensure only alpha-numeric characters trigger the save routine.
   1  
   2  function timed_updateSummaryCRecord(keyCode, parent_id, field,  val) {
   3    if (val.length > 0 && ((keyCode > 40) || (keyCode == 8)) ) {
   4      clearTimeout(t);
   5      t = setTimeout("updateSummaryCRecord('" + parent_id + "', '" + field + "', '" + val + "')", 1000);
   6    }
   7  }

The setTimeout will trigger the save routine after 1 second, however if the user continues to type before the 1 second timer has elapsed, the running timer will be cancelled and the new timer will start.

Note: keyCode value '8' is accepted because it is the backspace key. It would also be helpful to accept the delete key press.

Selection //JavaScript Class




Retrieves and sets the cursor position, as well the selected text of inputs and textareas. After searching, I saw it's the only code which retrieves right information in textareas under Internet Explorer without damaging the "Ctrl+Z"

[UPDATED CODE AND HELP CAN BE FOUND HERE]



   1  
   2  //+ Jonas Raoni Soares Silva
   3  //@ http://jsfromhell.com/forms/selection [v1.0]
   4  
   5  Selection = function(input){
   6  	this.isTA = (this.input = input).nodeName.toLowerCase() == "textarea";
   7  };
   8  with({o: Selection.prototype}){
   9  	o.setCaret = function(start, end){
  10  		var o = this.input;
  11  		if(Selection.isStandard)
  12  			o.setSelectionRange(start, end);
  13  		else if(Selection.isSupported){
  14  			var t = this.input.createTextRange();
  15  			end -= start + o.value.slice(start + 1, end).split("\n").length - 1;
  16  			start -= o.value.slice(0, start).split("\n").length - 1;
  17  			t.move("character", start), t.moveEnd("character", end), t.select();
  18  		}
  19  	};
  20  	o.getCaret = function(){
  21  		var o = this.input, d = document;
  22  		if(Selection.isStandard)
  23  			return {start: o.selectionStart, end: o.selectionEnd};
  24  		else if(Selection.isSupported){
  25  			var s = (this.input.focus(), d.selection.createRange()), r, start, end, value;
  26  			if(s.parentElement() != o)
  27  				return {start: 0, end: 0};
  28  			if(this.isTA ? (r = s.duplicate()).moveToElementText(o) : r = o.createTextRange(), !this.isTA)
  29  				return r.setEndPoint("EndToStart", s), {start: r.text.length, end: r.text.length + s.text.length};
  30  			for(var $ = "[###]"; (value = o.value).indexOf($) + 1; $ += $);
  31  			r.setEndPoint("StartToEnd", s), r.text = $ + r.text, end = o.value.indexOf($);
  32  			s.text = $, start = o.value.indexOf($);
  33  			if(d.execCommand && d.queryCommandSupported("Undo"))
  34  				for(r = 3; --r; d.execCommand("Undo"));
  35  			return o.value = value, this.setCaret(start, end), {start: start, end: end};
  36  		}
  37  		return {start: 0, end: 0};
  38  	};
  39  	o.getText = function(){
  40  		var o = this.getCaret();
  41  		return this.input.value.slice(o.start, o.end);
  42  	};
  43  	o.setText = function(text){
  44  		var o = this.getCaret(), i = this.input, s = i.value;
  45  		i.value = s.slice(0, o.start) + text + s.slice(o.end);
  46  		this.setCaret(o.start += text.length, o.start);
  47  	};
  48  	new function(){
  49  		var d = document, o = d.createElement("input"), s = Selection;
  50  		s.isStandard = "selectionStart" in o;
  51  		s.isSupported = s.isStandard || (o = d.selection) && !!o.createRange();
  52  	};
  53  }


Example

   1  
   2  <form id="form">
   3  	<fieldset>
   4  		<legend>Selection Test</legend>
   5  		<textarea name="text" rows="10" cols="30">
   6  www.jsfromhell.com
   7  Jonas Carlos Lalala
   8  Bin Laden x Bush
   9  		</textarea><br />
  10  		<input name="getText" type="button" value="[Get selected text]" />
  11  		<input name="getSel" type="button" value="[Get cursor]" />
  12  		<br /><input name="setText" type="button" value="[Set selected text]" />
  13  		<input name="setSel" type="button" value="[Set cursor]" />
  14  	</fieldset>
  15  </form>
  16  
  17  <script type="text/javascript">
  18  var f = document.forms.form;
  19  var selection = new Selection(f.text);
  20  
  21  f.getText.onclick = function(){
  22  	alert(selection.getText());
  23  	f.text.focus();
  24  };
  25  f.setText.onclick = function(){
  26  	var s = prompt("New text:", selection.getText());
  27  	s !== null && selection.setText(s);
  28  	f.text.focus();
  29  };
  30  f.getSel.onclick = function(){
  31  	var s = selection.getCaret();
  32  	alert("Start: " + s.start + "\nEnd: " + s.end);
  33  	f.text.focus();
  34  };
  35  f.setSel.onclick = function(){
  36  	var s = selection.getCaret();
  37  	selection.setCaret(+prompt("Start:", s.start) || 0, +prompt("End:", s.end) || 0);
  38  	f.text.focus();
  39  };
  40  </script>

PHP: Create a SELECT input field

Creates a SELECT input field with an optional parameter to preselect an item

   1  
   2  function selectfield($optionsarray, $selected = "") {
   3    $returnval = "";
   4    foreach ($optionsarray as $field=>$value) {
   5      if ($field == $selected) {
   6        $returnval .= "<option selected value='" . $field . "'>" . $value . "</option>\n";
   7      } else {
   8        $returnval .= "<option value='" . $field . "'>" . $value . "</option>\n";
   9      }
  10    }
  11    
  12    return $returnval;
  13  }

Java DOM : Creating an XML Document from XML File

// description of your code here

   1  
   2      try
   3      {
   4        //
   5        // Create the XML Document
   6        //
   7  
   8        DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
   9        DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
  10        Document doc = docBuilder.parse(filePath);
  11  
  12        // ...
  13  
  14      }
  15      catch (Exception e)
  16      {
  17        // ...
  18      }

Reading a webpage in Java

A trivial piece of example code demonstrating how to get a BufferedReader from a Url as a String and do something with it. This code simply prints the contents of the website at the first argument to stdout.

   1  
   2  import java.io.*;
   3  import java.net.URL;
   4  
   5  public class WebsiteReader
   6  {
   7  	public static BufferedReader read(String url) throws Exception{
   8  		return new BufferedReader(
   9  			new InputStreamReader(
  10  				new URL(url).openStream()));}
  11  
  12  	public static void main (String[] args) throws Exception{
  13  		BufferedReader reader = read(args[0]);
  14  		String line = reader.readLine();
  15  
  16  		while (line != null) {
  17  			System.out.println(line);
  18  			line = reader.readLine(); }}
  19  }

using Event.observe for when a page loads

I just prefer this implementation as opposed to window.onload.

   1  Event.observe( window, 'load', function() {
   2    // Put the Javascript that needs to happen when the page
   3    // loads here
   4  } );


For example, here's a way to make most of your input fields and all of your textareas have a different class when they're selected. Useful if you want to style them differently with CSS.
   1  Event.observe( window, 'load', function() {
   2    var inputs = document.getElementsByTagName( 'input' );
   3    var textareas = document.getElementsByTagName( 'textarea' );
   4  
   5    for ( var i=0; i<inputs.length; i++ ) {
   6      type = inputs[i].type;
   7  
   8      if (
   9        ( type == 'button' || type == 'reset' ||
  10        type == 'password' || type == 'text' ||
  11        type == 'submit' ) &&
  12        ( inputs[i].onfocus == '' ||
  13        !inputs[i].onfocus )
  14      ) {
  15        inputs[i].onfocus = function() {
  16          this.className = 'selected';
  17        }
  18  
  19        inputs[i].onblur = function() {
  20          this.className = '';
  21        }
  22      }
  23    }
  24  
  25    for ( var i=0; i<textareas.length; i++ ) {
  26      if ( textareas[i].onfocus == '' || !textareas[i].onfocus ) {
  27        textareas[i].onclick = function() {
  28          this.className = 'selected';
  29        }
  30        textareas[i].onblur = function() {
  31          this.className = '';
  32        }
  33      }
  34    }
  35  } );

Cross platform getch() in python

For Unix, it uses sys, tty, termios modules.
   1  
   2  import sys, tty, termios
   3  fd = sys.stdin.fileno()
   4  old_settings = termios.tcgetattr(fd)
   5  tty.setraw(sys.stdin.fileno())
   6  ch = sys.stdin.read(1)

For Windows, it uses msvcrt module.
   1  
   2  import msvcrt
   3  ch = msvcrt.getch()

See more details and OSX code in this recipe by Danny Yoo.

JavaScript DateBoxControl

In input forms on web pages you often have to validate dates and users are always entering something off the wall. Simon Incutio came up with a script to parse the dates. I added some stuff and turned it into a control of sorts. It is sort of US centric with date entering but it does accept iso style entries.

   1  
   2  // Date Box Control
   3  // 
   4  // based on:
   5  //  'Magic' date parsing, by Simon Willison (6th October 2003)
   6  //   http://simon.incutio.com/archive/2003/10/06/betterDateInput
   7  // 
   8  // Notes
   9  // To create a date box control, call the SetupDateBoxControl function.
  10  // It should be passed an input element with type of text.
  11  // This will first create a div after the input box.
  12  // Then it will associate the div with the input element.
  13  // The div will use the css classes: DateBoxControlMsg, DateBoxControlErrorMsg.
  14  // Then the div is associated with the input element.
  15  // Then the contents are validated so the div will get populated initially.
  16  // The onchange event of the input element will invoke the validation function.
  17  // The validation function populates the div.
  18  // If a successfully parsed date, the div gets a nicely formatted date.
  19  // If an unsuccessfully parse date, the div gets an error message.
  20  //
  21  // History
  22  // 02/03/2005 - WSR : modified for use as datebox control
  23  // 09/09/2005 - WSR : datebox is not required anymore (blank input is valid)
  24  //                  : added style class to datebox itself
  25  
  26  // hooks functionality up to given textbox
  27  function SetupDateBoxControl( ctlDateBox )
  28     {
  29  
  30     // if a valid object was given
  31     if (ctlDateBox)
  32        {
  33  
  34        // add div after control for messages
  35        var divMessage = document.createElement('div');
  36        divMessage.className = 'DateBoxControlMsg';
  37  
  38        // if there is a next sibling
  39        if (ctlDateBox.nextSibling)
  40           {
  41  
  42           // insert before next sibling
  43  		   ctlDateBox.parentNode.insertBefore( divMessage, ctlDateBox.nextSibling );
  44  
  45           }
  46        // if there is not a next sibling
  47        else
  48           {
  49  
  50           // append child to parent
  51           ctlDateBox.parentNode.appendChild( divMessage );         
  52  
  53           }
  54  
  55        // link message div to textbox for easy script access
  56        ctlDateBox.message = divMessage;
  57  
  58        // validate current contents
  59        DateBoxControl_Validate( ctlDateBox );
  60  
  61        // hook up event handlers
  62        ctlDateBox.onchange = function () { DateBoxControl_Validate(this); };
  63        
  64        }
  65  
  66     }
  67  
  68  // add indexOf function to Array type
  69  // finds the index of the first occurence of item in the array, or -1 if not found
  70  Array.prototype.indexOf = function(item) {
  71      for (var i = 0; i < this.length; i++) {
  72          if (this[i] == item) {
  73              return i;
  74          }
  75      }
  76      return -1;
  77  };
  78  
  79  // add filter function to Array type
  80  // returns an array of items judged true by the passed in test function
  81  Array.prototype.filter = function(test) {
  82      var matches = [];
  83      for (var i = 0; i < this.length; i++) {
  84          if (test(this[i])) {
  85              matches[matches.length] = this[i];
  86          }
  87      }
  88      return matches;
  89  };
  90  
  91  // add right function to String type
  92  // returns the rightmost x characters
  93  String.prototype.right = function( intLength ) {
  94     if (intLength >= this.length)
  95        return this;
  96     else
  97        return this.substr( this.length - intLength, intLength );
  98  };
  99  
 100  // add trim function to String type
 101  // trims leading and trailing whitespace
 102  String.prototype.trim = function() { return this.replace(/^\s+|\s+$/, ''); };
 103  
 104  // arrays for month and weekday names
 105  var monthNames = "January February March April May June July August September October November December".split(" ");
 106  var weekdayNames = "Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" ");
 107  
 108  /* Takes a string, returns the index of the month matching that string, throws
 109     an error if 0 or more than 1 matches
 110  */
 111  function parseMonth(month) {
 112      var matches = monthNames.filter(function(item) { 
 113          return new RegExp("^" + month, "i").test(item);
 114      });
 115      if (matches.length == 0) {
 116          throw new Error("Invalid month string");
 117      }
 118      if (matches.length < 1) {
 119          throw new Error("Ambiguous month");
 120      }
 121      return monthNames.indexOf(matches[0]);
 122  }
 123  
 124  /* Same as parseMonth but for days of the week */
 125  function parseWeekday(weekday) {
 126      var matches = weekdayNames.filter(function(item) {
 127          return new RegExp("^" + weekday, "i").test(item);
 128      });
 129      if (matches.length == 0) {
 130          throw new Error("Invalid day string");
 131      }
 132      if (matches.length < 1) {
 133          throw new Error("Ambiguous weekday");
 134      }
 135      return weekdayNames.indexOf(matches[0]);
 136  }
 137  
 138  function DateInRange( yyyy, mm, dd )
 139     {
 140  
 141     // if month out of range
 142     if ( mm < 0 || mm > 11 )
 143        throw new Error('Invalid month value.  Valid months values are 1 to 12');
 144  
 145     // get last day in month
 146     var d = (11 == mm) ? new Date(yyyy + 1, 0, 0) : new Date(yyyy, mm + 1, 0);
 147  
 148     // if date out of range
 149     if ( dd < 1 || dd > d.getDate() )
 150        throw new Error('Invalid date value.  Valid date values for ' + monthNames[mm] + ' are 1 to ' + d.getDate().toString());
 151  
 152     return true;
 153  
 154     }
 155  
 156  /* Array of objects, each has 're', a regular expression and 'handler', a 
 157     function for creating a date from something that matches the regular 
 158     expression. Handlers may throw errors if string is unparseable. 
 159  */
 160  var dateParsePatterns = [
 161      // Today
 162      {   re: /^today/i,
 163          handler: function() { 
 164              return new Date();
 165          } 
 166      },
 167      // Tomorrow
 168      {   re: /^tomorrow/i,
 169          handler: function() {
 170              var d = new Date(); 
 171              d.setDate(d.getDate() + 1); 
 172              return d;
 173          }
 174      },
 175      // Yesterday
 176      {   re: /^yesterday/i,
 177          handler: function() {
 178              var d = new Date();
 179              d.setDate(d.getDate() - 1);
 180              return d;
 181          }
 182      },
 183      // mmddyyyy (American style)
 184      {   re: /(\d{2})(\d{2})(\d{4})/,
 185          handler: function(bits) {
 186  
 187              var yyyy = parseInt(bits[3], 10);
 188              var dd = parseInt(bits[2], 10);
 189              var mm = parseInt(bits[1], 10) - 1;
 190  
 191              if ( DateInRange( yyyy, mm, dd ) )
 192                 return new Date(yyyy, mm, dd);
 193  
 194          }
 195      },
 196      // mmddyy (American style) short year
 197      {   re: /(\d{2})(\d{2})(\d{2})/,
 198          handler: function(bits) {
 199  
 200              var d = new Date();
 201              var yyyy = d.getFullYear() - (d.getFullYear() % 100) + parseInt(bits[3], 10);
 202              var dd = parseInt(bits[2], 10);
 203              var mm = parseInt(bits[1], 10) - 1;
 204  
 205              if ( DateInRange(yyyy, mm, dd) )
 206                 return new Date(yyyy, mm, dd);
 207  
 208          }
 209      },
 210      // 4th
 211      {   re: /^(\d{1,2})(st|nd|rd|th)?$/i, 
 212          handler: function(bits) {
 213  
 214              var d = new Date();
 215              var yyyy = d.getFullYear();
 216              var dd = parseInt(bits[1], 10);
 217              var mm = d.getMonth();
 218  
 219              if ( DateInRange( yyyy, mm, dd ) )
 220                 return new Date(yyyy, mm, dd);
 221  
 222          }
 223      },
 224      // 4th Jan
 225      {   re: /^(\d{1,2})(?:st|nd|rd|th)? (\w+)$/i, 
 226          handler: function(bits) {
 227  
 228              var d = new Date();
 229              var yyyy = d.getFullYear();
 230              var dd = parseInt(bits[1], 10);
 231              var mm = parseMonth(bits[2]);
 232  
 233              if ( DateInRange( yyyy, mm, dd ) )
 234                 return new Date(yyyy, mm, dd);
 235  
 236          }
 237      },
 238      // 4th Jan 2003
 239      {   re: /^(\d{1,2})(?:st|nd|rd|th)? (\w+),? (\d{4})$/i,
 240          handler: function(bits) {
 241  
 242              var yyyy = parseInt(bits[3], 10);
 243              var dd = parseInt(bits[1], 10);
 244              var mm = parseMonth(bits[2]);
 245  
 246              if ( DateInRange( yyyy, mm, dd ) )
 247                 return new Date(yyyy, mm, dd);
 248  
 249          }
 250      },
 251      // Jan 4th
 252      {   re: /^(\w+) (\d{1,2})(?:st|nd|rd|th)?$/i, 
 253          handler: function(bits) {
 254  
 255              var d = new Date();
 256              var yyyy = d.getFullYear(); 
 257              var dd = parseInt(bits[2], 10);
 258              var mm = parseMonth(bits[1]);
 259  
 260              if ( DateInRange( yyyy, mm, dd ) )
 261                 return new Date(yyyy, mm, dd);
 262  
 263          }
 264      },
 265      // Jan 4th 2003
 266      {   re: /^(\w+) (\d{1,2})(?:st|nd|rd|th)?,? (\d{4})$/i,
 267          handler: function(bits) {
 268  
 269              var yyyy = parseInt(bits[3], 10); 
 270              var dd = parseInt(bits[2], 10);
 271              var mm = parseMonth(bits[1]);
 272  
 273              if ( DateInRange( yyyy, mm, dd ) )
 274                 return new Date(yyyy, mm, dd);
 275  
 276          }
 277      },
 278      // next Tuesday - this is suspect due to weird meaning of "next"
 279      {   re: /^next (\w+)$/i,
 280          handler: function(bits) {
 281  
 282              var d = new Date()