Building a Select or Other input with PHP and jQuery

A select or other input is a great way to represent a list of common options but still give the user a chance to enter some other value entirely. It is a dropdown select field with options that provides a text box in case the option “other” is selected. As far as the data is concerned, a select or other is a text field. The select field is just for show and convenience. Have a look at the code below, which provides a complete select or other function. As with all code, it can be improved. Please use it wherever you want and post any improvements you make in the comments.

<?php
//selectorother.php

echo '<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>';

function selectorother($name,$options,$value){
	$input = '<form action="#">';

	$selector_id = $name.'_selector';
	$input .= '<select id="'.$selector_id.'" name="'.$selector_id.'">';
	foreach($options as $option_value=>$option_text){
		$option_selected = '';
		if($value == $option_value){
			$option_selected = 'selected';
		}
		$input .= '<option value="'.$option_value.'" '.$option_selected.'>'.$option_text.'</option>';
	}
	if($value && !in_array($value,$options)){
		$other_selected = 'selected';
	}else{
		$other_selected = '';
	}

	$input .= '<option value="other" '.$other_selected.'>Other...</option>';
	$input .= '</select>';
	$input .= '<input id="'.$name.'" name="'.$name.'" value="'.$value.'">';
	$input .= '<input type="submit" value="Submit"/>';
	$input .= '</form>';

	$startother = ($value && !in_array($value,$options));

	$input .= '<script>';
	$input .= <<<SCRIPT
jQuery(document).ready(function(){
jQuery('#$selector_id').bind('change',function(){
jQuery('#$name').val(jQuery('#$selector_id').val());
if(jQuery(this).val() == 'other'){
jQuery('#$name').show();
}else{
jQuery('#$name').hide();
}
});
if('$startother'){
jQuery('#$name').show();
}else{
jQuery('#$name').hide();
}
});
SCRIPT;
	$input .= '</script>';

	return $input;
}

$select_options = array(
	'red'=>'red',
	'green'=>'green',
	'blue'=>'blue',
);

echo selectorother('color',$select_options,$_GET['color']);

if($_GET['color']){
	echo '<br>Option Selected: '.$_GET['color'];
}

 

 

an example of a select or other field

Leave a Reply

Your email address will not be published. Required fields are marked *