gpt4 book ai didi

javascript - 如何从PHP中的复选框中的文本框获取值

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

我有 4 个复选框,其中一个是 Others有文本框,我想获取用户检查的所有值,以及如果他检查其他选项以从与 Others 关联的文本框中获取值复选框。

HTML 代码

<div class="row">
<div class="col-sm-4">
<label class="Modallabel">Available Products:</label>
</div>
<div class="col-sm-8">
<label id="Pro_chkbox" class="checkbox-inline"><input name="check_list[]" type="checkbox" value="Cacao">Cacao</label>
<label id="Pro_chkbox" class="checkbox-inline"><input name="check_list[]" type="checkbox" value="Coconuts">Coconuts</label>
<label id="Pro_chkbox" class="checkbox-inline"><input name="check_list[]" type="checkbox" value="Bananas">Bananas</label><br>
<label id="Pro_chkbox" class="checkbox-inline"><input name="check_list[]" type="checkbox" id="optcheck" value="Others">Others</label>
<input type="text" id="Other_pro" name="otherproduct"><br>
<label id="Note">(Separate Products with commas)</label>
</div>
</div>

PHP 代码

$checked_count = count($_POST['check_list']);

if ($checked_count > 1)
{
$productlist = implode(', ', $_POST['check_list']);
echo $productlist;
}
elseif ($checked_count == 1)
{
foreach($_POST['check_list'] as $selected) {
$productlist = $selected;

//To check if Others checkbox is checked or not to get the values in textbox
if ($productlist == "Others")
{
$productlist = $_POST["otherproduct"];
}
echo $productlist;
}
}

最佳答案

这对你有用

$checked_count = count($_POST['check_list']);
$productlist = ''; //initialize an empty string for product list
if ($checked_count > 1) //check if multiple check-boxes are checked
{
$productlist = implode(', ', $_POST['check_list']); //implode all checkbox values in list string
if(in_array('Others', $_POST['check_list'])) { //check if others is checked
$productlist .= ', '.$_POST['otherproduct']; //con-cat text in text box lined with others in list string
$productlist = str_replace('Others,', '', $productlist); //remove others from the list string (skip if you want others to be in your result'
}
} elseif ($checked_count == 1) {
$productlist = ($_POST['check_list'][0] == 'Others') ? $_POST['otherproduct'] : $_POST['check_list'][0]; //if only one checkbox is checked then check its value and use the value
}
echo "<br/>".$productlist;

此外,您可以进行客户端和服务器端验证,以确保从表单中获得正确的输入值。

此外,您还可以使用 javascript 使表单更具交互性。

关于javascript - 如何从PHP中的复选框中的文本框获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46253140/

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