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.

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


same code as above but with comments.
<a href="/status/destroy/719423092" onclick="

                     // if the user clicks the 'OK' button the confirm function will return true
if (confirm('Sure you want to delete this update? There is NO undo!')) { 

  // -- dhtml: creating html elements on-the-fly -------------------------------
  var f = document.createElement('form'); // create the dhtml 'form' (<form/>) element
  f.style.display = 'none';               // hide the form
  this.parentNode.appendChild(f);         // append the form element to the parent of the current node (<a/>)
  f.method = 'POST';                      // add the method to the form
  f.action = this.href;                   // add the action using the href of the current node (<a/>)
    
  var m = document.createElement('input');   // create the input (<input/>) 'element' 
  m.setAttribute('type', 'hidden');          // set the input type to 'hidden'
  m.setAttribute('name', '_method');         // set the input name to '_method'
  m.setAttribute('value', 'delete');         // set the input value to 'delete'
  f.appendChild(m);                          // append the input element to the form element
  
  var s = document.createElement('input');   // create another input element
  s.setAttribute('type', 'hidden');          // set the type to 'hidden'
  s.setAttribute('name', 'authenticity_token'); // set the name to 'authenticity_token'
  
                                     // set the input element's value using a unique id.
  s.setAttribute('value', 'd0057265c3784d2a6dc6cdb2c26083f638152151'); 
  
  f.appendChild(s);                  // apend the input element to the form element
  // -- end of dhtml: creating html elements on-the-fly -------------------------------
  
  f.submit(); // post the form data back to the server to delete the record, 
              // just as if the user had pressed the submit button.
};

  return false; // returning false cancels the default <a href="..."> request. 
                 // However if JavaScript had been disabled for some reason the 
                 // <a href="..."> would have acted normally, meaning the record 
                 // would have been deleted from following the URL request directly.
 "

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.
<input type="text" name="proj1" id="proj1" value="Car_log" 
  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.
function timed_updateSummaryCRecord(keyCode, parent_id, field,  val) {
  if (val.length > 0 && ((keyCode > 40) || (keyCode == 8)) ) {
    clearTimeout(t);
    t = setTimeout("updateSummaryCRecord('" + parent_id + "', '" + field + "', '" + val + "')", 1000);
  }
}

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]



//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com/forms/selection [v1.0]

Selection = function(input){
	this.isTA = (this.input = input).nodeName.toLowerCase() == "textarea";
};
with({o: Selection.prototype}){
	o.setCaret = function(start, end){
		var o = this.input;
		if(Selection.isStandard)
			o.setSelectionRange(start, end);
		else if(Selection.isSupported){
			var t = this.input.createTextRange();
			end -= start + o.value.slice(start + 1, end).split("\n").length - 1;
			start -= o.value.slice(0, start).split("\n").length - 1;
			t.move("character", start), t.moveEnd("character", end), t.select();
		}
	};
	o.getCaret = function(){
		var o = this.input, d = document;
		if(Selection.isStandard)
			return {start: o.selectionStart, end: o.selectionEnd};
		else if(Selection.isSupported){
			var s = (this.input.focus(), d.selection.createRange()), r, start, end, value;
			if(s.parentElement() != o)
				return {start: 0, end: 0};
			if(this.isTA ? (r = s.duplicate()).moveToElementText(o) : r = o.createTextRange(), !this.isTA)
				return r.setEndPoint("EndToStart", s), {start: r.text.length, end: r.text.length + s.text.length};
			for(var $ = "[###]"; (value = o.value).indexOf($) + 1; $ += $);
			r.setEndPoint("StartToEnd", s), r.text = $ + r.text, end = o.value.indexOf($);
			s.text = $, start = o.value.indexOf($);
			if(d.execCommand && d.queryCommandSupported("Undo"))
				for(r = 3; --r; d.execCommand("Undo"));
			return o.value = value, this.setCaret(start, end), {start: start, end: end};
		}
		return {start: 0, end: 0};
	};
	o.getText = function(){
		var o = this.getCaret();
		return this.input.value.slice(o.start, o.end);
	};
	o.setText = function(text){
		var o = this.getCaret(), i = this.input, s = i.value;
		i.value = s.slice(0, o.start) + text + s.slice(o.end);
		this.setCaret(o.start += text.length, o.start);
	};
	new function(){
		var d = document, o = d.createElement("input"), s = Selection;
		s.isStandard = "selectionStart" in o;
		s.isSupported = s.isStandard || (o = d.selection) && !!o.createRange();
	};
}


Example

<form id="form">
	<fieldset>
		<legend>Selection Test</legend>
		<textarea name="text" rows="10" cols="30">
www.jsfromhell.com
Jonas Carlos Lalala
Bin Laden x Bush
		</textarea><br />
		<input name="getText" type="button" value="[Get selected text]" />
		<input name="getSel" type="button" value="[Get cursor]" />
		<br /><input name="setText" type="button" value="[Set selected text]" />
		<input name="setSel" type="button" value="[Set cursor]" />
	</fieldset>
</form>

<script type="text/javascript">
var f = document.forms.form;
var selection = new Selection(f.text);

f.getText.onclick = function(){
	alert(selection.getText());
	f.text.focus();
};
f.setText.onclick = function(){
	var s = prompt("New text:", selection.getText());
	s !== null && selection.setText(s);
	f.text.focus();
};
f.getSel.onclick = function(){
	var s = selection.getCaret();
	alert("Start: " + s.start + "\nEnd: " + s.end);
	f.text.focus();
};
f.setSel.onclick = function(){
	var s = selection.getCaret();
	selection.setCaret(+prompt("Start:", s.start) || 0, +prompt("End:", s.end) || 0);
	f.text.focus();
};
</script>

PHP: Create a SELECT input field

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

function selectfield($optionsarray, $selected = "") {
  $returnval = "";
  foreach ($optionsarray as $field=>$value) {
    if ($field == $selected) {
      $returnval .= "<option selected value='" . $field . "'>" . $value . "</option>\n";
    } else {
      $returnval .= "<option value='" . $field . "'>" . $value . "</option>\n";
    }
  }
  
  return $returnval;
}

Java DOM : Creating an XML Document from XML File

// description of your code here

    try
    {
      //
      // Create the XML Document
      //

      DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
      DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
      Document doc = docBuilder.parse(filePath);

      // ...

    }
    catch (Exception e)
    {
      // ...
    }

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.

import java.io.*;
import java.net.URL;

public class WebsiteReader
{
	public static BufferedReader read(String url) throws Exception{
		return new BufferedReader(
			new InputStreamReader(
				new URL(url).openStream()));}

	public static void main (String[] args) throws Exception{
		BufferedReader reader = read(args[0]);
		String line = reader.readLine();

		while (line != null) {
			System.out.println(line);
			line = reader.readLine(); }}
}

using Event.observe for when a page loads

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

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


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.
Event.observe( window, 'load', function() {
  var inputs = document.getElementsByTagName( 'input' );
  var textareas = document.getElementsByTagName( 'textarea' );

  for ( var i=0; i<inputs.length; i++ ) {
    type = inputs[i].type;

    if (
      ( type == 'button' || type == 'reset' ||
      type == 'password' || type == 'text' ||
      type == 'submit' ) &&
      ( inputs[i].onfocus == '' ||
      !inputs[i].onfocus )
    ) {
      inputs[i].onfocus = function() {
        this.className = 'selected';
      }

      inputs[i].onblur = function() {
        this.className = '';
      }
    }
  }

  for ( var i=0; i<textareas.length; i++ ) {
    if ( textareas[i].onfocus == '' || !textareas[i].onfocus ) {
      textareas[i].onclick = function() {
        this.className = 'selected';
      }
      textareas[i].onblur = function() {
        this.className = '';
      }
    }
  }
} );

Cross platform getch() in python

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

For Windows, it uses msvcrt module.
import msvcrt
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.

// Date Box Control
// 
// based on:
//  'Magic' date parsing, by Simon Willison (6th October 2003)
//   http://simon.incutio.com/archive/2003/10/06/betterDateInput
// 
// Notes
// To create a date box control, call the SetupDateBoxControl function.
// It should be passed an input element with type of text.
// This will first create a div after the input box.
// Then it will associate the div with the input element.
// The div will use the css classes: DateBoxControlMsg, DateBoxControlErrorMsg.
// Then the div is associated with the input element.
// Then the contents are validated so the div will get populated initially.
// The onchange event of the input element will invoke the validation function.
// The validation function populates the div.
// If a successfully parsed date, the div gets a nicely formatted date.
// If an unsuccessfully parse date, the div gets an error message.
//
// History
// 02/03/2005 - WSR : modified for use as datebox control
// 09/09/2005 - WSR : datebox is not required anymore (blank input is valid)
//                  : added style class to datebox itself

// hooks functionality up to given textbox
function SetupDateBoxControl( ctlDateBox )
   {

   // if a valid object was given
   if (ctlDateBox)
      {

      // add div after control for messages
      var divMessage = document.createElement('div');
      divMessage.className = 'DateBoxControlMsg';

      // if there is a next sibling
      if (ctlDateBox.nextSibling)
         {

         // insert before next sibling
		   ctlDateBox.parentNode.insertBefore( divMessage, ctlDateBox.nextSibling );

         }
      // if there is not a next sibling
      else
         {

         // append child to parent
         ctlDateBox.parentNode.appendChild( divMessage );         

         }

      // link message div to textbox for easy script access
      ctlDateBox.message = divMessage;

      // validate current contents
      DateBoxControl_Validate( ctlDateBox );

      // hook up event handlers
      ctlDateBox.onchange = function () { DateBoxControl_Validate(this); };
      
      }

   }

// add indexOf function to Array type
// finds the index of the first occurence of item in the array, or -1 if not found
Array.prototype.indexOf = function(item) {
    for (var i = 0; i < this.length; i++) {
        if (this[i] == item) {
            return i;
        }
    }
    return -1;
};

// add filter function to Array type
// returns an array of items judged true by the passed in test function
Array.prototype.filter = function(test) {
    var matches = [];
    for (var i = 0; i < this.length; i++) {
        if (test(this[i])) {
            matches[matches.length] = this[i];
        }
    }
    return matches;
};

// add right function to String type
// returns the rightmost x characters
String.prototype.right = function( intLength ) {
   if (intLength >= this.length)
      return this;
   else
      return this.substr( this.length - intLength, intLength );
};

// add trim function to String type
// trims leading and trailing whitespace
String.prototype.trim = function() { return this.replace(/^\s+|\s+$/, ''); };

// arrays for month and weekday names
var monthNames = "January February March April May June July August September October November December".split(" ");
var weekdayNames = "Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" ");

/* Takes a string, returns the index of the month matching that string, throws
   an error if 0 or more than 1 matches
*/
function parseMonth(month) {
    var matches = monthNames.filter(function(item) { 
        return new RegExp("^" + month, "i").test(item);
    });
    if (matches.length == 0) {
        throw new Error("Invalid month string");
    }
    if (matches.length < 1) {
        throw new Error("Ambiguous month");
    }
    return monthNames.indexOf(matches[0]);
}

/* Same as parseMonth but for days of the week */
function parseWeekday(weekday) {
    var matches = weekdayNames.filter(function(item) {
        return new RegExp("^" + weekday, "i").test(item);
    });
    if (matches.length == 0) {
        throw new Error("Invalid day string");
    }
    if (matches.length < 1) {
        throw new Error("Ambiguous weekday");
    }
    return weekdayNames.indexOf(matches[0]);
}

function DateInRange( yyyy, mm, dd )
   {

   // if month out of range
   if ( mm < 0 || mm > 11 )
      throw new Error('Invalid month value.  Valid months values are 1 to 12');

   // get last day in month
   var d = (11 == mm) ? new Date(yyyy + 1, 0, 0) : new Date(yyyy, mm + 1, 0);

   // if date out of range
   if ( dd < 1 || dd > d.getDate() )
      throw new Error('Invalid date value.  Valid date values for ' + monthNames[mm] + ' are 1 to ' + d.getDate().toString());

   return true;

   }

/* Array of objects, each has 're', a regular expression and 'handler', a 
   function for creating a date from something that matches the regular 
   expression. Handlers may throw errors if string is unparseable. 
*/
var dateParsePatterns = [
    // Today
    {   re: /^today/i,
        handler: function() { 
            return new Date();
        } 
    },
    // Tomorrow
    {   re: /^tomorrow/i,
        handler: function() {
            var d = new Date(); 
            d.setDate(d.getDate() + 1); 
            return d;
        }
    },
    // Yesterday
    {   re: /^yesterday/i,
        handler: function() {
            var d = new Date();
            d.setDate(d.getDate() - 1);
            return d;
        }
    },
    // mmddyyyy (American style)
    {   re: /(\d{2})(\d{2})(\d{4})/,
        handler: function(bits) {

            var yyyy = parseInt(bits[3], 10);
            var dd = parseInt(bits[2], 10);
            var mm = parseInt(bits[1], 10) - 1;

            if ( DateInRange( yyyy, mm, dd ) )
               return new Date(yyyy, mm, dd);

        }
    },
    // mmddyy (American style) short year
    {   re: /(\d{2})(\d{2})(\d{2})/,
        handler: function(bits) {

            var d = new Date();
            var yyyy = d.getFullYear() - (d.getFullYear() % 100) + parseInt(bits[3], 10);
            var dd = parseInt(bits[2], 10);
            var mm = parseInt(bits[1], 10) - 1;

            if ( DateInRange(yyyy, mm, dd) )
               return new Date(yyyy, mm, dd);

        }
    },
    // 4th
    {   re: /^(\d{1,2})(st|nd|rd|th)?$/i, 
        handler: function(bits) {

            var d = new Date();
            var yyyy = d.getFullYear();
            var dd = parseInt(bits[1], 10);
            var mm = d.getMonth();

            if ( DateInRange( yyyy, mm, dd ) )
               return new Date(yyyy, mm, dd);

        }
    },
    // 4th Jan
    {   re: /^(\d{1,2})(?:st|nd|rd|th)? (\w+)$/i, 
        handler: function(bits) {

            var d = new Date();
            var yyyy = d.getFullYear();
            var dd = parseInt(bits[1], 10);
            var mm = parseMonth(bits[2]);

            if ( DateInRange( yyyy, mm, dd ) )
               return new Date(yyyy, mm, dd);

        }
    },
    // 4th Jan 2003
    {   re: /^(\d{1,2})(?:st|nd|rd|th)? (\w+),? (\d{4})$/i,
        handler: function(bits) {

            var yyyy = parseInt(bits[3], 10);
            var dd = parseInt(bits[1], 10);
            var mm = parseMonth(bits[2]);

            if ( DateInRange( yyyy, mm, dd ) )
               return new Date(yyyy, mm, dd);

        }
    },
    // Jan 4th
    {   re: /^(\w+) (\d{1,2})(?:st|nd|rd|th)?$/i, 
        handler: function(bits) {

            var d = new Date();
            var yyyy = d.getFullYear(); 
            var dd = parseInt(bits[2], 10);
            var mm = parseMonth(bits[1]);

            if ( DateInRange( yyyy, mm, dd ) )
               return new Date(yyyy, mm, dd);

        }
    },
    // Jan 4th 2003
    {   re: /^(\w+) (\d{1,2})(?:st|nd|rd|th)?,? (\d{4})$/i,
        handler: function(bits) {

            var yyyy = parseInt(bits[3], 10); 
            var dd = parseInt(bits[2], 10);
            var mm = parseMonth(bits[1]);

            if ( DateInRange( yyyy, mm, dd ) )
               return new Date(yyyy, mm, dd);

        }
    },
    // next Tuesday - this is suspect due to weird meaning of "next"
    {   re: /^next (\w+)$/i,
        handler: function(bits) {

            var d = new Date();
            var day = d.getDay();
            var newDay = parseWeekday(bits[1]);
            var addDays = newDay - day;
            if (newDay <= day) {
                addDays += 7;
            }
            d.setDate(d.getDate() + addDays);
            return d;

        }
    },
    // last Tuesday
    {   re: /^last (\w+)$/i,
        handler: function(bits) {

            var d = new Date();
            var wd = d.getDay();
            var nwd = parseWeekday(bits[1]);
         
            // determine the number of days to subtract to get last weekday
            // calculates 0 if weekdays are the same so we have to change this to 7
            var addDays = (wd == nwd) ? -7 : (-1 * (wd + 7 - nwd)) % 7;
            
            // adjust date and return
            d.setDate(d.getDate() + addDays);
            return d;

        }
    },
    // Tuesday
    {   re: /^(\