简体   繁体   中英

How to set the 'selected option' of a select dropdown list country and state

My filter search flowing :

case 'region_state':
$output .= '
<div class="clear"></div>
<label><st>' . __( "Country", AT_TEXTDOMAIN ) . ':</s2></label>
<div class="select_box_1">
    <select name="region_id" id="region_id" class="custom-select select_1">';
    $output .= '<option value="0">' . __( "All", AT_TEXTDOMAIN ) . '</option>';
    foreach ($view->add_widget( 'reference_widget', array( 'method' => 'get_regions' ), true ) as $key => $value) {
        $output .= '<option value="' . $value['id'] . '">' . $value['name'] . '</option>';
      }
    // foreach (AT_VC_Helper::get_manufacturers() as $value => $key) {
    //  $output .= '<option value="' . $key. '">' . $value . '</option>';
    // }
    $output .= '
    </select>
    </div>
    <label><s3>' . __( "State", AT_TEXTDOMAIN ) . ':</s3></label>
    <div class="select_box_1">
      <select name="state_id" id="state_id" class="custom-select select_1">
        <option>All</option>
      </select>
    </div>';
    $output .= '<input type="submit" value="' . __( "Search", AT_TEXTDOMAIN ) . '" class="btn_search btn-1 float-right" id="search_car_shortcode1"/>';
            break;

Data Become from reference_widget WordPress admin , I want 1 country for Ex USA State : new york, By default.

You will need to test on each loop if the value you are on is the one that should be "selected".

// the value you want to be selected
$region_id = $_REQUEST['region_id'];
// loop through the options
foreach ( $view->add_widget( 'reference_widget', array( 'method' => 'get_regions' ), true ) as $key => $value ){
    // if the value matches, we want to output "selected"
    $selected = ( $region_id == $value )? ' selected' : '';
    $output .= '<option value="' . $value['id'] . '"' . $selected . '>' . $value['name'] . '</option>';
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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