首页 > 解决方案 > 将函数值传递给表单中的隐藏字段

问题描述

如何传递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'>&nbsp;&nbsp;&nbsp;&nbsp;
    <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);
}
?>

标签: javascriptforms

解决方案


您必须在 javascript 函数中设置 txt 的值,如下所示:

document.getElementById('master').value = txt;

然后该值应设置为您的隐藏字段。


推荐阅读