dslijian2015
dslijian2015
2017-10-25 09:55
浏览 39
已采纳

根据条件,如何使下拉列表单选或多选?

I had a requirement where in an employee list dropdown given, if selectMultiple is set, the dropdown should allow multiple selects, and if selectMultiple is not set, it shouldn't.

<select name="employeeList[]" id="employeeList" class="form-
control" multiple="<?=$selectMultiple?>">
    <?php
    foreach($employeeList as $employee) {

        echo "<option value='" . $employee->$employeeId . "'>" . 
        $employee->employeeName . "</option>";

    }    
    ?>
</select>

It's a phtml file, and $selectMultiple is passed from a controller(as in Phalcon). I have tried something like passing, $selectMultiple ="multiple", so the code will look like

<select name="employeeList[]" id="employeeList" class="form-control" multiple="multiple">

and $selectMultiple="" for the single select case.

<select name="employeeList[]" id="employeeList" class="form-control" multiple="">

But the very presence of multiple attribute itself makes the dropdown list elligible for multiselect.

In short, in either cases, it triggers multiselect regardless of the condition. Please help.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • duanmeng3573
    duanmeng3573 2017-10-25 10:49
    已采纳

    You can simply write your code like

    You need to pass $selectMultiple = "multiple" or $selectMultiple = ''

    <select name="employeeList[]" id="employeeList" class="form-control" <? echo !empty($selectMultiple) ? $selectMultiple : '' ?>>
    <?php
    foreach($employeeList as $employee) {
    
        echo "<option value='" . $employee->$employeeId . "'>" . 
        $employee->employeeName . "</option>";
    
    }    
    ?>
    

    点赞 评论
  • douwei9759
    douwei9759 2017-10-25 16:24

    I tried introducing a new variable "chooseId" to get rid of the multiple attribute and hence worked! Modified the select tag to,

    <select name="employeeList[]" id="employeeList" class="form-control"
    <?php if ($chooseId== 1) { ?> multiple="multiple" <?php } ?>>
    <?php
      foreach($employeeList as $employee) {
    
        echo "<option value='" . $employee->$employeeId . "'>" . 
        $employee->employeeName . "</option>";
    
    }    
    ?>
    </select>
    

    Now the code recognises the multiple attribute and enables multiselect only when chooseId is 1, otherwise single select works normally.

    点赞 评论

相关推荐