繁体   English   中英

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

[英]How to pre select an option from dropdown menu in PHP

我正在为列表目录使用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>

这个例子可以帮助

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; 
  }  
}

这里是链接如何使用Javascript或jQuery在选项属性中添加“选定”?

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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM