我有一个像这样的选择下拉列表:
<select name="city" id="order_form_select">
<option value="" disabled selected>Ort ↓</option>
<option>Option 1</option>
<option>Option 2</option>
<option>Option 3</option>
<option>Option 4</option>
</select>
我正在收到一些这样的单选按钮:
<?php
$statement = $pdo->prepare('SELECT some_column FROM my_table WHERE some_value = "abc" AND city = :city');
$statement->execute(array('city' => $city));
$row = $statement->rowCount();
if ($row == 0) {
echo "<input type=\"radio\" name=\"something\" value=\"option1\">Option 1</p>";
}
$statement = $pdo->prepare('SELECT some_column FROM my_table WHERE some_value = "xyz" AND city = :city');
$statement->execute(array('city' => $city));
$row = $statement->rowCount();
if ($row == 0) {
echo "<input type=\"radio\" name=\"something\" value=\"option2\">Option 2</p>";
}
?>
如您所见,这些单选按钮取决于选择选项。这意味着,只要用户更改了选择选项,PHP代码就必须刷新,但选择框选项必须保持登录状态。
这样做的正确/常用方法是什么?
答案 0 :(得分:0)
假设您每次选择值时都要刷新页面:
创建此javascript
<script type="text/javascript">
window.onload = function () {
var citySelector = document.getElementById('order_form_select');
citySelector.addEventListener('change', function () {
if (this.value) {
window.location = 'yourphp.php?city=' + this.value
}
}, false);
}
</script>
在您的html代码中,为您的选项添加值:
<select name="city" id="order_form_select">
<option value="" disabled selected>Ort ↓</option>
<option value="City1">Option 1</option>
<option value="City2">Option 2</option>
<option value="City3">Option 3</option>
<option value="City4">Option 4</option>
</select>
<select name="city" id="order_form_select">
<option value="" disabled <?php echo !isset($_GET['city']) ? 'selected' : ''; ?>>Ort ↓</option>
<option value="City1" <?php echo isset($_GET['city']) && $_GET['city'] == 'City1' ? 'selected' : ''; ?>>Option 1</option>
<option value="City2" <?php echo isset($_GET['city']) && $_GET['city'] == 'City2' ? 'selected' : ''; ?>>Option 2</option>
<option value="City3" <?php echo isset($_GET['city']) && $_GET['city'] == 'City3' ? 'selected' : ''; ?>>Option 3</option>
<option value="City4" <?php echo isset($_GET['city']) && $_GET['city'] == 'City4' ? 'selected' : ''; ?>>Option 4</option>
</select>
已修改版本:
如果您想避免使用javascript来执行此任务,您可以改变您的方法:
<form action="yourphpfile.php" method="GET">
<select name="city" id="order_form_select">
<option value="" disabled <?php echo !isset($_GET['city']) ? 'selected' : ''; ?>>Ort ↓</option>
<option value="City1" <?php echo isset($_GET['city']) && $_GET['city'] == 'City1' ? 'selected' : ''; ?>>Option 1</option>
<option value="City2" <?php echo isset($_GET['city']) && $_GET['city'] == 'City2' ? 'selected' : ''; ?>>Option 2</option>
<option value="City3" <?php echo isset($_GET['city']) && $_GET['city'] == 'City3' ? 'selected' : ''; ?>>Option 3</option>
<option value="City4" <?php echo isset($_GET['city']) && $_GET['city'] == 'City4' ? 'selected' : ''; ?>>Option 4</option>
</select>
<input type="submit" value="search by city">
</form>
希望这有助于你