最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Remove blank options from select field? - Stack Overflow

programmeradmin6浏览0评论

I have a fairly simple select field with options fetched from a database (Magento) and echoed via

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 null fields, I still get empty option fields

I also have this JavaScript to sort my options alphabetically, could this cause me to have blank 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 could one ensure with JavaScript that no blank options in a drop-down select are displayed?

Particulars:

Data source for my foreach contains no blank fields

I get as many blank options as legitimate options

The end result source code looks like this:

I have a fairly simple select field with options fetched from a database (Magento) and echoed via

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 null fields, I still get empty option fields

I also have this JavaScript to sort my options alphabetically, could this cause me to have blank 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 could one ensure with JavaScript that no blank options in a drop-down select are displayed?

Particulars:

Data source for my foreach contains no blank fields

I get as many blank options as legitimate options

The end result source code looks like this:

Share Improve this question edited Apr 24, 2015 at 13:30 zak asked Apr 24, 2015 at 13:13 zakzak 1513 silver badges14 bronze badges 23
  • 2 You tried if(!empty($a['label'])) ? – Guilherme Ferreira Commented Apr 24, 2015 at 13:15
  • Better to use if($a['label'] != NULL && $a['label'] != '') rather than relay on JS – Sunil Pachlangia Commented Apr 24, 2015 at 13:17
  • Maybe. if($a['label'] != '') – BCM Commented Apr 24, 2015 at 13:17
  • @GuilhermeFerreira just tried that, same result – zak Commented Apr 24, 2015 at 13:21
  • 1 @zak I just saw Eko3alpha's answer mention it as well already, so give Eko3alpha's answer the check mark. ;-) – Decent Dabbler Commented Apr 24, 2015 at 14:48
 |  Show 18 more ments

8 Answers 8

Reset to default 4

This should work just fine, also you don't have a closing tag which was causing some issues when I was testing. You should also not echo out every time in the loop. create a variable and echo once outside the loop.

$options = '';
foreach ($groups as $a)
{
    if(!empty($a['label']))
    {
        $options .= "<option value='".$a['value']."'>" . $a['label'] . "</option>";
    }
}
echo $options;

Try with empty

if(!empty(trim($a['label']))) {
    ...  

Once you'll be looking into this solution, you might also e across isset which is not quite what you need, since your if statement with isset would evaluate to true even if it's an empty string.

Using empty() will skip 0 also

if(!(!isset($a['label']) || $a['label']=='' || !isset($a['value']) || $a['value']=='')) {
          //logic here
}

I think NULL is ing as a string. try this

foreach ($groups as $a){

if($a['label'] != 'NULL'){ //wrap NULL to single quote   

    echo "<option value='".$a['value']."'>" . $a['label'] . "<option>";

}

}

If $a['label'] contains 1 more more spaces it won't equal NULL or be empty.

foreach ($groups as $a) {
    $label = trim($a['label']);
    $value = trim($a['value']);
    if (!empty($label)) {    
        echo "<option value='$value'>$label<option>";
    }
}

Probably your array $groups es with empty values, so try array_filter:

$groups = array_filter($groups);
foreach ($groups as $a) {
...

Try this code :

foreach ($groups as $a){

    if(trim($a['label']) != ''){    

        echo "<option value='".$a['value']."'>" . $a['label'] . "<option>";

    }

}

The immediate issue I see with your code is you are mixing double and single quotes in your HTML and missing the closing option tag. <select id=""> vs <option value=''>

You should change your PHP output like so:

foreach ($groups as $a) {
    echo '<option value="'.$a['value'].'">' . $a['label'] . '</option>';
}

I like using array_filter for things like these. It allows you to specify your own method outside of additional condition checks from within 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>";
}

http://ideone./h0Wk1T

Also unless you are dynamically sorting the values alphabetically with Javascript (onclick/user action) I suggest you sort your groups with PHP after using array_filter. A lot less frustration and doesn't rely on client-side patibility.

function cmp($a, $b){
    return strcmp($a['label'], $b['label']);
}

usort($groups, 'cmp');

http://ideone./OH5vXL

发布评论

评论列表(0)

  1. 暂无评论