Never been to TextSnippets 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 (or not, you can keep them private!)

« Newer Snippets
Older Snippets »
2 total  XML / RSS feed 

Active Selection Box (drop down) examples

// description of your code here

<%= select_tag( :saction, options_for_select([["Actions:",0],["Edit",1],["Delete",2]],0),
                                :onchange => "if(confirm('Are you sure?  This will effect all products checked below.')) products_form.submit(); else products_form.saction.value = 0;")%>


<%= select_tag( :sort_by, options_for_select([["Sort by:",0],["Name",'name'],["Price",'price'], ["Date Listed",'id']],0),
                                :onchange => remote_function(        :with => "'sort_by='+$(\"sort_by\").value",
                                                                                                :loading => "false;",
:url => { :controller => 'products', :action => :change_order } )
)  %>

Selecting and checking items from HTML menus

This code allows you to pass in an HTML menu (select, radio, or checkbox) along with a single choice or an array of choices to be selected. The choice(s) should be contained literally in the value attribute.

This is handy for making persistent forms without polluting the HTML with PHP logic. For example, you could initialize all your menus to have nothing selected and then pass in GET or POST variables in case the form was not accepted, easily making form selections persistent.

/**
 * For select menus.
 */
function select_from_menu($menu,$choices,$deselect=true) {
  if ($deselect) $menu = preg_replace('/ selected(="selected")?/','',$menu);
  if(!is_array($choices)) {
    $menu = preg_replace('/(value="'.preg_quote($choices).'")/',"$1 selected=\"selected\"",$menu);
  } else foreach($choices as $value) {
    $menu = preg_replace('/(value="'.preg_quote($value).'")/',"$1 selected=\"selected\"",$menu);
  }
  
  return $menu;
}

/**
 * For radio buttons and checkboxes.
 */
function check_from_menu($menu,$choices,$deselect=true) {
  if ($deselect) $menu = preg_replace('/ checked(="checked")?/','',$menu);
  if(!is_array($choices)) {
    $menu = preg_replace('/(value="'.preg_quote($choices).'")/',"$1 checked=\"checked\"",$menu);
  } else foreach($choices as $value) {
    $menu = preg_replace('/(value="'.preg_quote($value).'")/',"$1 checked=\"checked\"",$menu);
  }

  return $menu;
}
« Newer Snippets
Older Snippets »
2 total  XML / RSS feed