gpt4 book ai didi

javascript - 使用 onchange 提交获取多个复选框值

转载 作者:行者123 更新时间:2023-12-03 02:21:31 27 4
gpt4 key购买 nike

我正在尝试获取复选框值并在使用 jquery onchange 提交提交另一个时保持先前的选中状态。

问题是 $_GET['marca'] 数组中仅维护最后提交的内容。如果有人知道如何解决这个问题,我将不胜感激。

if ( isset($_GET['marca']) ) {
$_GET['marca'];
}
elseif ( empty($_GET['marca']) ) {
$_GET['marca'] = null;
}

<form method="get">
<input type="checkbox" id="amd" class="checkbox-filtro" name="marca"
value="amd">
<label for="amd">AMD</label>
<input type="checkbox" id="evga" class="checkbox-filtro" name="marca"
value="evga">
<label for="evga">EVGA</label>
<input type="checkbox" id="intel" class="checkbox-filtro" name="marca"
value="intel">
<label for="intel">Intel</label>
</form>

$('.checkbox-filtro').on('change', function() {
this.form.submit();
});

最佳答案

复选框的名称应为 marca[] 用作数组(如 @FunkFortyNiner 所指出)。

在 PHP 中,您可以存储在变量中以确保您有一个数组,即使没有发送任何内容。

最后,在 HTML 中,您可以使用 in_array()检查该值是否在您的变量中。如果是这样,请将属性 checked 添加到您的复选框。

<?php

// Check the presence of the index in $_GET and if it is an array to avoid errors with in_array().
$marca = isset($_GET['marca']) && is_array($_GET['marca'])
? $_GET['marca'] : [];
?>

<form method="get">

<input type="checkbox" id="amd" class="checkbox-filtro" name="marca[]"
value="amd" <?php echo in_array('amd', $marca) ? 'checked' : '' ?>>
<label for="amd">AMD</label>

<input type="checkbox" id="evga" class="checkbox-filtro" name="marca[]"
value="evga" <?php echo in_array('evga', $marca) ? 'checked' : '' ?>>
<label for="evga">EVGA</label>

<input type="checkbox" id="intel" class="checkbox-filtro" name="marca[]"
value="intel" <?php echo in_array('intel', $marca) ? 'checked' : '' ?>>
<label for="intel">Intel</label>

</form>
<小时/>

你原来的PHP代码没有效果:

if ( isset($_GET['marca']) ) {
$_GET['marca']; // do nothing
}
elseif ( empty($_GET['marca']) ) {
$_GET['marca'] = null; // change "empty" to null.
}

因此,在这种状态下,您无法确定 $_GET['marca'] 已定义或包含您想要的内容。

关于javascript - 使用 onchange 提交获取多个复选框值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49137068/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com