如何从PHP的下拉菜单中预先选择一个选项

时间:2019-01-03 10:00:18

标签: php wordpress directory-listing

我正在为列表目录使用WordPress主题,并且尝试从下拉菜单中预先选择一个选项,以便当有人打开该页面时,他们将立即从该选项中获取列表。

我尝试使用jQuery,但无法正常工作,因此我现在被困在这里。欢迎任何帮助。

图片:https://imgur.com/a/G0Rtny3

编辑:我找到了一个解决方法,将“生产者”作为唯一选项,并将if语句从!empty($ term_ID)更改为empty($ term_ID)。

这可能不是最佳解决方案,但对我有用。谢谢大家。

<select data-placeholder="<?php echo esc_html__('Select Category','dwt- 
listing');?>" name="l_category" class="allow_clear" id="l_category">

<option value=""><?php echo esc_html__('Select an 
option','dwt-listing'); ?>
</option>

<option value="all"><?php echo esc_html__('All Categories','dwt- 
listing'); ?>
<?php

        //selective
        if( isset( $_GET['l_category'] ) && $_GET['l_category'] != "" )
        {
            $term_ID = $_GET['l_category'];
        }
        foreach( $listing_cats as $cats )
        {
        ?>  
          <option <?php if ($cats->term_id == $term_ID) { ?>selected="selected"<?php } ?> value="<?php echo esc_attr( $cats->term_id ); ?>"><?php echo esc_html( $cats->name ); ?></option>
        <?php
        }
        ?>
       </select>

2 个答案:

答案 0 :(得分:0)

这个例子可以帮助

var select = document.getElementById('countryselect');
var option;

for (var i=0, i<select.options.length; i<iLen; i++) {
  option = select.options[i];

  if (option.value == '4') {
  // or
  // if (option.text = 'Malaysia') {
     option.setAttribute('selected', true);

     // For a single select, the job's done
     return; 
  }  
}

这里是链接 How to add "selected" in option attribute using Javascript or jQuery?

答案 1 :(得分:0)

I have made a little change in your code.
check this and first in sure that you have got $term_ID or not because your selected option depend on this variable.

Replace this:-

    <option <?php if ($cats->term_id == $term_ID) { ?>selected="selected"<?php } ?> value="<?php echo esc_attr( $cats->term_id ); ?>"><?php echo esc_html( $cats->name ); ?></option> 

With this:-

    <option value="<?php echo esc_attr( $cats->term_id ); ?>" <?php if ($cats->term_id==$term_ID) { echo "selected='selected'"; } ?> ><?php echo esc_html( $cats->name ); ?></option>
相关问题