如何让表单下拉框提交空值(value="")而非选项文本?
Let's break down the issue and fix it step by step:
Problem with Your Current HTML
Your first <option> has value="" but uses the hidden attribute. While this makes it invisible, browsers still treat it as the default selected option—and in some cases, they might submit the option's text ("All") instead of the specified value="" (though this is technically against spec, it's a common quirk with hidden default options).
Corrected HTML
Replace the hidden attribute with selected to make it the explicit default visible option. This ensures the browser submits the empty value as expected:
<select class="form-control" name="type"> <option value="" selected>All</option> <option value="Apartment">Apartment</option> <option value="Villa">Villa</option> <option value="Hotel">Hotel</option> </select>
Adjust Your PHP Logic
Your current PHP has a syntax issue in the condition (!$_POST['type'] == '' is incorrect) and doesn't handle clearing the session when an empty value is submitted. Here's the revised code:
/***************** Setup the type filter *****************************/ // Handle search submission first if (isset($_POST['issearch'])) { if ($_POST['type'] !== '') { $type = $_POST['type']; $type_query = array( 'meta_key' => 'type_name', 'value' => array($type) ); array_push($meta_query, $type_query); $_SESSION['type'] = $type; } else { // Clear stored type from session when "All" is selected unset($_SESSION['type']); } } // Apply stored filter if no new submission if (isset($_SESSION['type'])) { $type = $_SESSION['type']; $type_query = array( 'meta_key' => 'type_name', 'value' => array($type) ); array_push($meta_query, $type_query); }
What This Fixes
- After updating the HTML, your POST dump will show
[type] =>(empty string) instead of[type] => Allwhen "All" is selected. - The revised PHP correctly skips adding the type filter when an empty value is submitted, and clears the session to avoid leftover filters affecting future requests.
内容的提问来源于stack exchange,提问作者Alex Knopp

