[Intermediate] Set Metadata Date Fields To Current Date and Time


(Nic Hubbard) #1

That have been many times when I had a metadata date field that I wanted to have the default set to the current date and time. Currently this is not possible in Matrix, without the help of javascript. So, I wrote a quick jQuery script that does just that. It looks for the parts of the select id's that are used for month, day, hour, minute, etc and sets those to the current date and time:



    $(document).ready(function() {
    // ----- Set the current date for metadata date fields -----
    	var current_full_date = new Date();
    	var current_year = current_full_date.getFullYear();
    	var current_day = current_full_date.getDate();
    	var current_month = current_full_date.getMonth();
    	var current_hour = current_full_date.getHours();
    	var current_min = current_full_date.getMinutes();
    	
    	// Set to the current day
    	$("select[id*='[d]']").children('option').each(function() { 
    		if ($(this).val() == current_day) { 
    			$(this).attr('selected', true); 
    		} 
    	});
    	// Set to the current month
    	$("select[id*='[m]']").children('option').each(function() { 
    		if ($(this).val() == current_month + 1) { 
    			$(this).attr('selected', true);
    		} 
    	});
    	// Set to the current hour
    	$("select[id*='[h]']").children('option').each(function() { 
    		if ($(this).val() == current_hour) { 
    			$(this).attr('selected', true);
    		} 
    	});
    	// Set to the current minute
    	$("select[id*='[i]']").children('option').each(function() { 
    		if ($(this).val() == current_min) { 
    			$(this).attr('selected', true);
    		} 
    	});
    	// Set to the current year
    	$("input[id*='[y]']").val(current_year);
    });


Note: The Year script is written to work with the year field being an input field, rather than a select field.

EDIT: Added the jquery ready function so there was no confusion with how to load this.

(Duncan Robertson) #2

It works so well. Thanks Nic.


(Nic Hubbard) #3

No problem. Glad someone else finds it useful!

(Rachel Macdonald) #4

Ooo, will be keen to try this out soon!


How did you choose to insert the code on just the pages that need it?


(Nic Hubbard) #5

[quote]Ooo, will be keen to try this out soon!


How did you choose to insert the code on just the pages that need it?[/quote]



There is no requirement to put it in the header. As long as you use the jquery ready function, and the code is above that HTML that you want to change, then it will work by just pasting it into the body of a page.


(Rachel Macdonald) #6

I had no idea that I could put those bits in the body!



This makes things so much easier!



See, a tiny amount of knowledge is a very inefficient thing… :rolleyes:


(Duncan Robertson) #7

Agreed. I speak for myself when I say Jquery has solved some very dark dead ends lately.