javascript - 将函数值传递给表单中的隐藏字段
问题描述
如何传递txt = txt + "\n" + x.options[i].value;
到表单中的隐藏字段?在我的代码下面:
<form action="update.php" method="post">
<input type=button class="master" name=b1 id=b1 value='Move >'>
<input type=button class="master" name=b2 id=b2 value='< Remove'>
<select name=category[] id=category multiple="multiple" class=master>
<?php
$file = fopen("category.csv", "r");
while (($row = fgetcsv($file, 0, ",")) !== FALSE) {
$category = $row[0];
?>
<option value="<?php echo $category;?>"><?php echo $category;?></option>
<?php
}
?>
</select>
<input type="hidden" name="master" id="master" value="">
<input type="submit" value="Save File" onclick="displayResult()" name="submit" >
</form>
这里是我更新的 JS。
<script>
function displayResult() {
var options = document.getElementById('master').options;
var values = [];
var i = 0, len = options.length;
while (i < len)
{
values.push(options[i++].value);
}
txt=(values.join(','));
alert(txt);
document.getElementById('masterlist').value = txt;
}
</script>
它现在可以 100% 工作。value = txt
正确传输到我的表单隐藏字段,并且表单提交值action="update.php"
分别写入我的 master.csv 和 category.csv 文件。附上我的 update.php 文件
<?php
header("Location:".$URL.'index.php');
if ($_POST['masterlist']) {
$list = $_POST['masterlist'];
$str_master = explode (",", $list);
foreach ($str_master as $key => $value) {
$resultmaster.=$value. "\n";
}
file_put_contents('master.csv',$resultmaster);
}
if ($_POST['category']) {
$category = $_POST['category'];
$categoryunique = array_unique($category);
sort($categoryunique);
foreach ($categoryunique as $key => $value) {
$resultcategory.=$value. "\n";
}
file_put_contents('category.csv',$resultcategory);
}
?>
解决方案
您必须在 javascript 函数中设置 txt 的值,如下所示:
document.getElementById('master').value = txt;
然后该值应设置为您的隐藏字段。
推荐阅读
- r - 如何使用 R 按行值范围过滤数据帧?
- laravel - Laravel 一对多关系中的奇怪行为
- excel - 如何使用公式锁定单元格?
- python - Pyspark:根据另一列重复附加值到当前行生成一列
- graphql - 如何使用 graphql 和 gatsby 解决内容数据不足的问题?
- kubernetes - 调用 webhook inferenceservice.kfserving-webhook-server.defaulter 失败,kubeflow 中出现 x509 证书错误
- typescript - 打字稿错误 TS2451:无法重新声明块范围变量“chai_1”
- powershell - 我的 Sharpoint Online 角色列表 - æøå
- ruby-on-rails - 如何在 after_commit 回调中检测到图像 (ActiveStorage::Attached::One) 已更改为新图像?
- python - 在神经网络中准备训练和验证数据时出错