Tag Archive for form

Accessible Forms CSS

form.cmxform fieldset,form#standardForm fieldset{margin-bottom:10px;border:1px solid #ccc;background:#f0f0f0;}
form.cmxform fieldset fieldset,form#standardForm fieldset fieldset{background:none;border:none;}
form.cmxform legend,form#standardForm legend{padding: 0 2px;font-weight:bold;}
form.cmxform label,form#standardForm label{display:inline-block;line-height:1.8;vertical-align:top;}
form.cmxform fieldset ol,form#standardForm fieldset ol{margin:0;padding:0;}
form.cmxform fieldset li,form#standardForm fieldset li{list-style:none;padding:5px 10px 7px;margin:0;}
form.cmxform em,form#standardForm em{font-weight:bold;font-style:normal;font-size:130%;color:#f00;}
form.cmxform label,form#standardForm label{width:120px; /* Width of labels */}
form.cmxform label.wider,form#standardForm label.wider{width:150px;}
form.cmxform textarea,form#standardForm textarea{font-size:100%;font-family:verdana;}
form.cmxform .autoSize,form#standardForm .autoSize{width:auto;border:none;}
form.cmxform input.submit,form#standardForm input.submit{cursor:pointer;border:1px solid #fff;background:#84b84a;color:#fff;font-size:110%;font-weight:bold;padding:3px;}
form.cmxform input.submit:focus,form#standardForm input.submit:focus{background:#84b84a;}
form.cmxform select,form#standardForm select{width:300px;}
form.cmxform input.widerInput,form#standardForm input.widerInput{width:300px;}

source

Jquery Accessible Forms Code

$(document).ready(
function()
{
if($.browser.mozilla)
{
$("form.cmxform").find("li > label").not(".nocmx").each(
function(i)
{
span = document.createElement("span");
$(span).css({ display: "block", width: $(this).css("width") });
$(this).css("display","-moz-inline-box");
$(span).html($(this).html());
$(this).html("");
$(this).append(span);
}
);
}
}
);

source

EE Contact Form

{if segment_2 =="thanks"}
<h1>Many thanks</h1>
<p>We have now received your message and will be in touch shortly.</p>
{if:else}
{exp:freeform:form form_name="contactForm" form_class="cmxform" form_id="standardForm" required="name|email|comments" notify="jim@sixmedia.net" template="contact_form" return="/contact/thanks/"}
<fieldset>
<legend>Your Contact Details</legend>
<ol>
<li>
<label for="name">Name: <em>*</em></label>
<input type="text" id="name" name="name" size="40" />
</li>

<li>
<label for="email">Your Email: <em>*</em></label>
<input type="text" id="email" name="email" size="40" maxlength="35" value="" />
</li>
</ol>
</fieldset>

<fieldset>
<legend>Comments</legend>
<ol>
<li>
<label for="subject">Subject:</label>
<input type="text" id="subject" name="subject" size="40" value="" />
</li>
<li>
<label for="comments">Message: <em>*</em></label>
<textarea id="comments" name="comments" rows="10" cols="60"></textarea>
</li>
{if captcha}
<li>
<label for="captcha">Enter the word you see in the image: <em>*</em></label>
<input type="text" id="captcha" name="captcha" value="" maxlength="20" /><br />
{captcha}
</li>
{/if}
</ol>
</fieldset>
<p><input name="submit" type="submit" value="Send Message" /></p>
{/exp:freeform:form}
{/if}

source

Set Form Input Value

$(this).attr('value', 'newvalue');
$(this).val();

source

array2form

<?php
/**
 *  array2form
 *  written by: Mark Berube 
 *  Takes an array of form input parameters and builds form rows in a 2 column vertical layout table format
 *    In addition to the common form inputs, there are two custom form input this class will interpret:
 *    1. date: creates a text input which is populated from clicking an icon pointed to any javascript calendar script
 *    2. custom: creates a text input which is populated from clicking an icon pointed to any javascript function(useful for sql queries etc))
 *    See accompanying expample page for more detailed usage
 */ 
class array2form{
  public $icon_dir   = './';
  public $cal_icon   = 'calicon2_20.png';
  public $cust_icon  = '1downarrow.png';
  
    function array2form($input_array){
            $rows = "";
            foreach($input_array as $input){
                $params = $this->get_input_params($input);
                $type = strtolower($params['type']);
                    switch ($type){
                        case 'text':
                            $form_input = $this->get_text_input($params['name'],$params['values'], $params['size']);
                        break;
                        case 'radio':
                            $form_input = $this->get_radio_input($params['name'],$params['values']);
                        break;
                        case 'checkbox':
                            $form_input = $this->get_check_input($params['name'],$params['values']);
                        break;
                        case 'select':
                            $form_input = $this->get_select_input($params['name'],$params['values']);
                        break;
                        case 'textarea':
                            $form_input = $this->get_textarea_input($params['name'],$params['size']);
                        break;
                        case 'custom':
                            $form_input = $this->text_from_script_call($params['name'],$params['values'],$params['size'],$params['script']);
                        break;
                        case 'date':
                            $form_input = $this->get_date_input($params['name'],'',$params['script']);
                        break;
                    }
                $row = "
<tr>
<td class="form_heading">
".$params['label']."
</td>
<td class="form_input" nowrap>
$form_input
</td>
</tr>";

                $rows .= $row;
            }
    echo $rows;
    }

    private function get_input_params($input){
        list($input_type, $heading, $input_name, $values, $input_size, $script_call) = explode('|',$input);
            
              //if the input_name left blank, make one out of the label
              if($input_name == ''){
                $input_name = str_replace(array(' ',':',',','.','#'),array('_','','','',''),$heading);
                $input_name = trim(strtolower($input_name));
              }
          $params = array(
                'type'    => $input_type,
                'label'   => $heading,
                'name'    => $input_name,
                'values'  => $values,
                'size'    => $input_size,
                'script'  => $script_call
            );
        return $params;
    }

    private function text_from_script_call($input_name, $default_value, $size, $script_call){
        $form_input = "<INPUT TYPE="text" NAME="$input_name" ID="$input_name" SIZE="$size" VALUE="$default_value" readonly>
";
        $icon = $this->icon_dir . $this->cust_icon;
        $form_input .= "<IMG src="1downarrow.png" onclick="$script_call">
";
        return $form_input;
    }

    private function get_text_input($input_name, $default_value, $size){
        $form_input = "<INPUT TYPE="text" NAME="$input_name" ID="$input_name" SIZE="$size" VALUE="$default_value">
";
        return $form_input;
    }

    private function get_textarea_input($input_name, $size){
        list($cols,$rows) = explode(',',$size);
        $form_input = "<TEXTAREA NAME="$input_name" ID="$input_name" ROWS="$rows" COLS="$cols"></TEXTAREA>
";
        return $form_input;
    }

    private function get_date_input($input_name, $default_value, $script_call){
        $form_input = "<INPUT TYPE="text" NAME="$input_name" ID="$input_name" SIZE="10" MAXLENGTH="10" VALUE="$default_value" readonly>
";
        $icon = $this->icon_dir . $this->cal_icon;
        $form_input .= "<IMG src="$icon" onclick="$script_call">
";
        return $form_input;
    }

    private function get_radio_input($input_name, $values){
        $search = '(checked)';
        $form_input = "";
        $vals = explode(',',$values);
        foreach($vals as $val){
            if(strpos($val, $search) !== false){
                $on = true;
                $val = str_replace($search, '', $val);
            }else{
                $on = false;
            }

           $form_input .= "$val<INPUT TYPE="radio" NAME="$input_name" VALUE="$val"";
           $form_input .=  ($on) ? " " .substr($search,1,-1) : "";
           $form_input .= ">&nbsp;&nbsp;
";

        }
         return $form_input;
    }

    private function get_check_input($input_name, $values){
        $search = '(checked)';
        $form_input = "";
        $vals = explode(',',$values);
        $count = 0;
        foreach($vals as $val){

            if(strpos($val, $search) !== false){
                $on = true;
                $val = str_replace($search, '', $val);
            }else{
                $on = false;
            }
           $form_input .= "$val<INPUT TYPE="checkbox" NAME="". $input_name . '['.$count .']' ."" VALUE="$val"";
           $form_input .= ($on) ? " " .substr($search,1,-1) : "";
           $form_input .= ">&nbsp;&nbsp;
";
           $count  ;
        }
         return $form_input;
    }

    private function get_select_input($input_name, $values){
        $search = '(selected)';
        $form_input = "<SELECT NAME="$input_name" ID="$input_name">
";
        $vals = explode(',',$values);
        foreach($vals as $val){
            if(strpos($val, $search) !== false){
                $on = true;
                $val = str_replace($search, '', $val);
            }else{
                $on = false;
            }
           $form_input .= "	<OPTION VALUE="$val"";
           $form_input .= ($on) ? " SELECTED="" .substr($search,1,-1) . """ : "";
           $form_input .= ">$val</OPTION>
";
        }
        $form_input .= "</SELECT>
";
    return $form_input;
    }

}

?>

source

jQuery submit form with an anchor tag

$(document).ready( function(){

// bind "click" event for links with title="submit"
$("a[title=submit]").click( function(){
// it submits the form it is contained within
$(this).parents("form").submit();
});

});

source

PHP InsertFromVals

<?php

// Function: Insert From Vals
// Take an associative array and build an insert statement
//
// $table -> the table you want to fill
// $prefix -> the prefix of the fields ( ie, auto_color -> 'auto_' )
// $vals -> the array to insert, default _POST
//
// Please note that this will work with normal database naming and not with
// special names with spaces and accents and odd stuff
//
//
function insertFromVals( $table , $prefix , $vals = null )
{
$fields = array();
$vallues = array();

if( is_null( $vals ) )
{
$vals = $_POST;
}

foreach( $vals as $k => $v )
{
if( ereg( "^".$prefix , $k ) )
{
$fields[] = mysql_escape_string( $k );
$values[] = mysql_escape_string( $v );
}
}
$fields = join( "," , $fields );
$values = "'" . join(  "', '" , $values ) ."'";

$q = "INSERT INTO ".$table." (".$fields.") VALUES (".$values.")";

return $q;
}

/// testing code here:
/// probably not what you want to copy
/// illustrative purposes only

$test['user_name'] = "Doe";
$test['user_fname'] = "John";
$test['user_birthday'] = "1977-12-16 00:00:00";
$test['user_favorite_color'] = "orange";
$test['user_attempted_injection'] = "a string with a "'" can be dangerous in a db statement";

$q = insertFromVals( "users" , "user_" , $test );

echo $q;

?>

source

PHP Form Validation

<?php

//  Quick function to loop through regexs and compare to what is in _POST
//
//  $regs    ->   associative array of regular expressions
//  $ferrors ->   error messages to display to the users asociative array

function validatePost( $regs , $ferrors )
{
$errors = array();
foreach( $regs as $k => $v )
{
if( ! ereg( $v , $_POST[$k] ) )
{
$errors[$k] = $ferrors[$k];
}
}
return $errors;
}

// has the post been submitted?
if( count( $_POST ) )
{
// yes it has been submitted so lets validate
$regs['last_name']  = "^[[:alpha:] -]+$";  // require a alpha
$regs['first_name'] = "^[[:alpha:] -]+$";  // require a alpha
$regs['email']      = "^..*@..*$";         // VERY simple email check
// Use google to find better

// Ok here are the error message to display when it is bad
$ferrors['last_name']  = "Last name required";
$ferrors['first_name'] = "First name required";
$ferrors['email']      = "Email name required";

$errors = validatePost( $regs , $ferrors );

// Do we have errors?
if( count( $errors ) == 0 )
{
//  WE HAVE NO ERRORS DO SOMETHING
//  PUT IT INTO THE DATABASE, EMAIL, BOUNCE THE USER
//  TO A THANK YOU PAGE, ETC...
}
}
?>

<!-- OK WE ARE IN HTML -->
<!-- LETS MAKE THE FORM AND NOW YOU SEE HOW SIMPLE THIS IS I HOPE -->

<form method="POST">

<p>
<label>Last Name</label>
<input type="text" name="last_name" value="<?= $_POST['last_name'] ?>" />
<span style="color: #FF0000;"><?= $errors['last_name'] ?></span>
</p>

<p>
<label>First Name</label>
<input type="text" name="first_name" value="<?= $_POST['first_name'] ?>" />
<span style="color: #FF0000;"><?= $errors['first_name'] ?></span>
</p>

<p>
<label>Email</label>
<input type="text" name="email" value="<?= $_POST['email'] ?>" />
<span style="color: #FF0000;"><?= $errors['email'] ?></span>
</p>

<p>
<input type="submit" name="subby" value="GO" />
</p>

</form>

source

Stop PHP form inputs returning empty after validation

<?php if(isset($_POST['FORM_INPUT_OR_TEXTAREA_NAME_GOES_HERE'])){ echo $_POST['FORM_INPUT_OR_TEXTAREA_NAME_GOES_HERE']; } ?>

SAMPLE OF A FORM INPUT:

<input name="name" size="20" value="<?php if(isset($_POST['name'])){ echo $_POST['name']; } ?>">

SAMPLE OF A FORM TEXTAREA:

<textarea name="comments" rows=5 cols=20><?php if(isset($_POST['comments'])){ echo $_POST['comments']; } ?></textarea>

source

Switch label class for checkbox

//check first status with jQuery
//not needed if class initially are set

jQuery("#file_aktiv").click(function() {
if(jQuery(this).is(":checked") === true)
jQuery('label[for=file_aktiv]').addClass('file_active');
else
jQuery('label[for=file_aktiv]').addClass('file_active');
});

//then
jQuery("#file_aktiv").click(function() {
jQuery('label[for=file_aktiv]').switchClass('file_active','file_inactive');
});

//the switchClass function
(function($){var class1,class2,overrideClass=null;$.fn.switchClass=function(){if(arguments.length<2){alert("Illegal usage. switchClass requires at least 2 parameters, containing the class names to toggle.");return this;}
class1=arguments[0];class2=arguments[1];overrideClass=null;if(arguments.length==3)
overrideClass=arguments[2];return this.each(function(){$.fn.switchClass.process($(this));});};$.fn.switchClass.process=function(el)
{if(overrideClass!=null)
{if(overrideClass==class1&&el.hasClass(class2))
{el.removeClass(class2);el.addClass(class1);}
else if(overrideClass==class2&&el.hasClass(class1))
{el.removeClass(class1);el.addClass(class2);}}
else
{if(el.hasClass(class1))
{el.removeClass(class1);el.addClass(class2);}
else if(el.hasClass(class2))
{el.removeClass(class2);el.addClass(class1);}}};})(jQuery);

<!-- HTML -->
<input type="checkbox" checked="checked" value="1" id="file_aktiv" name="file_aktiv"/>
<label for="file_aktiv" class="fb_icon file_active">aktiv</label>
<input type="checkbox" checked="checked" value="1" id="file_public" name="file_public"/>
<label for="file_public" class="fb_icon file_public">öffentlich</label>

source