Expose those DOM objects real quick

I was wearing my DHTML hat the other day and wanted to share this javascript quick tip.  When I have to script DOM objects but don’t have time to figure out their goings on, I like to dump them via a for() loop.  Here’s how it works.

In my html file I’ll create this small script.

<script type="text/javascript">
function dump( objId )
{
	var domObj = document.getElementById( objId );

	// message holder
	var str = "";
	// loop
	for( xx in domObj )
	{
		// append to the message
		str += xx + " : " + domObj[ xx ] + "nn";

		// how long is the message?
		if( str.length >= 300 )
		{
			// show it
			alert( str );

			// reset it
			str = "";
		}
	}

}
</script>

Next I’ll drop an html button into my page that passes the id of my desired object to the dump.

<button onClick="dump('parentform')">dump</button>

Lastly I’ll fire up my html file, click the dump button, and hope I find what I’m looking for in the alert.

Click dump, get popup

dump popup

I don’t always find what I’m looking for, but I always end up finding interesting stuff. Especially when you run the same html file in different browsers.  I wrote a similar javascript dumper that writes to the page instead of an alert.  This one is also interesting to see in different browsers.

Select random value from a range of values

Earlier I blogged about creating random numbers using tsql functions.  Here are two techniques for selecting a random value from a pre-defined range of values in a tsql script.  The first technique uses a table variable ( MSSQL 2000 + ), and the second uses a Common Table Expression or CTE ( MSSQL 2005+ ).

Select a random value using a table variable


-- var to hold random integer
declare @field_val int

-- create table var to hold value range [ 0, 512, 1024, 2048, 4096 ]
-- inserting the first value sets the structure for the table variable
SELECT 0 AS 'num'
INTO #temp

-- insert data into table var
INSERT INTO #temp VALUES ( 512 )
INSERT INTO #temp VALUES ( 1024 )
INSERT INTO #temp VALUES ( 2048 )
INSERT INTO #temp VALUES ( 4096 )

-- assign random value
SELECT TOP 1 @field_val = num FROM #temp ORDER BY NEWID()

-- show value
SELECT @field_val

-- drop the table variable
DROP TABLE #temp

Select a random value using a CTE

-- define our data table
WITH data( car )
AS
(
	-- UNION together our range of values
	SELECT 'audi' AS 'car'
	UNION
	SELECT 'bmw' AS 'car'
	UNION
	SELECT 'infinity' AS 'car'
	UNION
	SELECT 'lexus' AS 'car'
	UNION
	SELECT 'porsche' AS 'car'
)
-- select a random value
SELECT TOP 1 car FROM data
ORDER BY NEWID()

Both of these techniques can be used with numbers or text. Just be sure to mind your quotes, and variable datatypes.  Being able to pick a random value in data generation scripts has proven very useful.  I hope this helps somebody else out as well.