Skip to content

Instantly share code, notes, and snippets.

@andrinheusser
Created May 5, 2011 12:13
Show Gist options
  • Save andrinheusser/956937 to your computer and use it in GitHub Desktop.
Save andrinheusser/956937 to your computer and use it in GitHub Desktop.
js rows
<tr>
<td colspan="3">
<div id="templates">
<div id="templatesStart"></div>
<!-- rows go here -->
<div id='templatesEnd' style="clear:both"></div>
</div>
<a href='#' class='add_row_link' data-rowGroup='templates'>Template hinzuf&uuml;gen</a>
</td>
</tr>
<script type="text/javascript">
$(document).ready(function(){
// No 'var'! That's important. It has to be a global variable
templatesFields = {
'name' : { 'type' : 'text', 'style': 'border: 1px solid #2b4b78;', 'value': 'Templatename'},
'rubrik' : { 'type' : 'checkbox', 'style' : '', 'value' : '1', 'checked': ''},
'uebersicht' : { 'type' : 'checkbox', 'style' : '', 'value' : '1', 'checked': ''},
'detail' : { 'type' : 'checkbox', 'style' : '', 'value' : '1', 'checked': ''},
'aktiv' : { 'type' : 'checkbox', 'style' : '', 'value' : '1', 'checked' : '' },
'limit': { 'type' : 'text', 'style': 'border: 1px solid #2b4b78;', 'value': '0'},
'perPage' : { 'type' : 'text', 'style' : 'border: 1px solid #2b4b78;', 'value': '10'},
'orderby' : { 'type' : 'text', 'style' : 'border: 1px solid #2b4b78;', 'value': 'pos ASC'},
'delete' : { 'type' : 'imagelink', 'image' : '../images/kill.gif'},
'save' : { 'type' : 'imagelink', 'image' : '../images/save.gif'},
'edit' : { 'type' : 'button', 'image' : 'edit.gif'},
'db_id': { 'type' : 'hidden' }
};
// Load existing templates as json
var vals = <?php echo json_encode(load_rows())?>;
// Fill in all existing rows, and create an empty, new row
fill_rows('templates', vals);
// Pre-existing values must be in this form
/*var vs = {
0: {'name' : 'Standard', 'rubrik' : 'checked', 'uebersicht' : '', 'detail' : 'checked', 'limit' : 0, 'perPage' : 10, 'orderby' : 'pos', 'db_id' : 12} ,
1: {'name' : 'Standard2', 'rubrik' : '', 'uebersicht' : 'checked', 'detail' : '', 'limit' : 5, 'perPage' : 15, 'orderby' : 'name', 'db_id' : 42}
};*/
/**
* Displays the existing rows
*
* @param string rowGroup the string declaring in which rowGroup the rows belong
* @param object values an Object containing the values for the rows that will be created
*
*/
function fill_rows(rowGroup, values){
print_headers(rowGroup);
// Data is optional
values = typeof(values) != "undefined" ? values : null;
var anzahl = 0;
// If values is set, create rows using data
if(values != null){
for(key in values){
add_row(rowGroup, anzahl, values[key]);
anzahl += 1;
}
}
// Add an empty row
//add_row(rowGroup, anzahl, null);
}
/**
* Prints a header for the rowGroup
*
* @param string rowGroup the string for which rowGroup the headers are
*
*/
function print_headers(rowGroup){
var head = "<div class='row-header' data-row-group='"+rowGroup+"' >";
// Fix with window[] to allow variable variables
for(var feldname in fields = window[rowGroup+"Fields"]) {
if(fields[feldname]["type"] != "hidden"){
head += "<div class='row-head f-"+feldname+"'>";
// Capitalise the first letter
head += feldname.slice(0,1).toUpperCase() + feldname.slice(1);
head += "</div>";
}
}
$('#'+rowGroup+"Start").after(head);
}
/**
* Adds a new row at the end of existing rows
*
* @param string rowGroup the string declaring in which rowGroup the row belongs
* @param integer id an integer containing a unique id for this row
* @param object values an Object containing the values for the row that will be created, optional
*
*/
function add_row(rowGroup, id, values){
var row = "<div data-row-group='"+rowGroup+"' data-row-id='"+id+"'>";
// Fix with window[] to allow variable variables
for(var feldname in fields = window[rowGroup+"Fields"]) {
row += "<div class='row-item f-"+feldname+"' style='float:left'>";
var type = fields[feldname]['type'];
if(type == 'text' || type == 'checkbox' || type=='hidden'){
// Add an input with standard values, or with existing values
if(values == null){
row += input_standard(id, feldname, fields[feldname]);
}else{
row += input_standard(id, feldname, fields[feldname], values[feldname]);
}
}else if(type == 'imagelink'){
row += imagelink(id, rowGroup, feldname, fields[feldname]);
}else if(type == 'button'){
row += button(id, feldname, fields[feldname]);
}
row += "</div>";
}
row += "</div>";
// Insert the row after all other rows
$('#'+rowGroup+'End').before(row);
}
/**
* Returns the amount of rows in a group
*
* @param string rowGroup the string that specifies which group to count
* @return integer an integer with the amount of rows
*
*/
function row_sum(rowGroup){
var all_rows = $('[data-row-group='+rowGroup+'][data-row-id]');
var sum = 0;
all_rows.each(function(){
var id = parseInt($(this).attr('data-row-id'));
// If the active id is bigger than the previously biggest id, this is the new id to beat
if(id > sum) sum = id;
});
// Add one, row-ids start at zero, easier to use when creating a new row
return sum+1;
}
/**
* Returns either a checkbox or a text field
*
* @param integer id the integer to be used in the data-row-fk attribute
* @param string name a string for the name of the input field/checkbox
* @param object data an object with properties for the type and the style of the input
* @param object value an object containing values to be set
* @return string a string with html code for the input
*
*/
function input_standard(id, name, data, value){
// value is optional
value = typeof(value) != "undefined" ? value : null;
if(data == null) return false;
if(value == null){
// if this is a checkbox, check if the checkbox should be checked per default
var checked = data['checked'] == 'checked' && data['type'] == "checkbox" ? "checked='checked'" : "";
value = data['value'];
}else{
// if value is set, is the box checked?
var checked = value == 'checked' ? "checked='checked'" : "";
value = value == "" && data['type'] == "checkbox" ? 1 : value;
}
return "<input class='f-"+name+"' type='"+data['type']+"' name='"+name+"' style='"+data['style']+"' value='"+value+"' data-row-fk='"+id+"' "+checked+" />";
}
/**
* Returns an image with a link
*
* @param integer id the integer to be used in the data-row-fk attribute
* @param string rowGroup a sting to specify the group
* @param string name a string for the action of the link
* @param object data an object with properties for the image
* @return string a string with html code for the imagelink
*
*/
function imagelink(id, rowGroup, name, data){
if(data == null) return false;
return "<a class='nofollow' href='#' data-action='"+name+"' data-row-fk='"+id+"' data-row-group='"+rowGroup+"' ><img src='"+data['image']+"' alt='"+name+"' /></a>";
}
/**
* Returns a button
*
* @param integer id the integer to be used in the data-row-fk attribute
* @param string name a string for the action of the button
* @return string a string with html code for the button
*
*/
function button(id, name, data){
return "<input type='button' data-action='"+name+"' data-row-fk='"+id+"' value='"+name+"' />";
}
/**
* Saves a row with an ajax request
*
* @param string rowGroup the string to select the group
* @param integer id the id of the row to be saved
*
*/
function save_row(rowGroup, id){
var input_fields = $('div[data-row-group='+rowGroup+'] > div > input[data-row-fk='+id+']');
var v = "";
// Fill all values in an array
input_fields.each(function(){
if($(this).attr("type") != "checkbox"){
v += $(this).attr('name') + "=" +$(this).val() + "&";
}else{
if($(this).attr("checked")){
v += $(this).attr('name') + "=" +$(this).val() + "&";
}else{
v += $(this).attr('name') + "=0&";
}
}
});
$.ajax({
'url' : 'save_template.php',
'type': 'post',
'data': v,
'dataType' : 'json',
'success' : function(response){
$('input[data-row-fk='+id+']:hidden').val(response);
}
});
}
/**
* Deletes a row with an ajax request
*
* @param string rowGroup the string to select the group
* @param integer id the id of the row to be deleted
*
*/
function delete_row(rowGroup, id){
// Get the db id
var db_id = $('input[data-row-fk='+id+']:hidden').val();
// Remove the row from the DOM
$('div[data-row-id='+id+'][data-row-group='+rowGroup+']').remove();
// Get every HTML element that has either a data-row-fk or data-row-id attribute
var to_subtract = $('div[data-row-group='+rowGroup+'], div[data-row-group='+rowGroup+'] > .row-item > [data-row-fk]');
to_subtract.each(function(){
// Is the attribute of the active element called data-row-id or -fk?
var attribute = 'data-row-id';
if($(this).attr(attribute) == null){
attribute = 'data-row-fk';
}
id_temp = $(this).attr(attribute);
// If the id of the active element is bigger than the id of the deleted element,
// subtract one from the attribute id (or -fk) of the active element
if(id_temp > id){
$(this).attr(attribute, (id_temp-1));
}
});
if(typeof(db_id) != "undefined"){
$.ajax({
'url': 'delete_template.php',
'type': 'post',
'data': 'id='+db_id
});
}
}
// When the link to add a new row is clicked
$('.add_row_link').click(function(){
var rowGroup = $(this).attr('data-rowGroup');
add_row(rowGroup, row_sum(rowGroup));
});
// When an action link is clicked
$('a[data-action][data-row-fk][data-row-group]').live("click", function(e){
// Prevent the browser from following the href attribute
e.preventDefault();
var action = $(this).attr('data-action');
var row_id = $(this).attr('data-row-fk');
var rowGroup = $(this).attr('data-row-group');
if(action=="save"){
save_row(rowGroup, row_id);
}else if(action=="delete"){
delete_row(rowGroup, row_id);
}
});
// When a button is clicked
$('input[data-action=edit]').click(function(){
var id = $(this).attr('data-row-fk');
var db_id = $('input[data-row-fk='+id+']:hidden').val();
if(typeof(db_id) != "undefined"){
window.location.href = 'edit.php?id='+db_id;
}
});
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment