Remove empty options from select box?
I have a fairly simple select box with parameters fetched from a database (Magento) and echoed through
foreach ($groups as $a){
if($a['label'] != NULL){
echo "<option value='".$a['value']."'>" . $a['label'] . "<option>";
}
}
My problem is that even with server-side code preventing empty fields, I still get empty parameter fields
I also have this JavaScript to sort my parameters alphabetically, can this have empty options?
function sortlist()
{
var cl = document.getElementById('group_id');
var clTexts = new Array();
for(i = 2; i < cl.length; i++)
{
clTexts[i-2] =
cl.options[i].text.toUpperCase() + "," +
cl.options[i].text + "," +
cl.options[i].value;
}
clTexts.sort();
for(i = 2; i < cl.length; i++)
{
var parts = clTexts[i-2].split(',');
cl.options[i].text = parts[1];
cl.options[i].value = parts[2];
}
}
sortlist();
How can you ensure with JavaScript that there are no blank options in the dropdown ?
Features:
Data source for my foreach does not contain empty fields
I get as many empty options as there are valid parameters
The source code for the final result looks like this:
source to share
This should work fine, also you don't have a closing tag which was causing some problems in testing. You also don't have to repeat every time in the loop. create a variable and echo outside of the loop.
$options = '';
foreach ($groups as $a)
{
if(!empty($a['label']))
{
$options .= "<option value='".$a['value']."'>" . $a['label'] . "</option>";
}
}
echo $options;
source to share
Your array may $groups
contain empty values, so try array_filter :
$groups = array_filter($groups);
foreach ($groups as $a) {
...
source to share
The immediate problem I see with your code is that you are mixing double and single quotes in your HTML and missing the closing tag.
<select id="">
vs<option value=''>
You have to change your PHP output like this:
foreach ($groups as $a) {
echo '<option value="'.$a['value'].'">' . $a['label'] . '</option>';
}
I like to use array_filter
for things like this. It allows you to specify your own method outside of the additional conditional checks from your view.
$groups = array(
array(
'label' => '',
'value' => ''
),
array(
'label' => 'test',
'value' => 'test'
)
);
function validate($var)
{
return !empty($var['label']);
}
$groups = array_filter($groups, 'validate');
foreach ($groups as $a) {
echo "<option value='".$a['value']."'>" . $a['label'] . "<option>";
}
Also, if you are not dynamically sorting the values alphabetically using Javascript (onclick / user action), then I suggest you sort the groups using PHP after use array_filter
. It's much less frustrating and doesn't depend on client side compatibility.
function cmp($a, $b){
return strcmp($a['label'], $b['label']);
}
usort($groups, 'cmp');
source to share