如何在输入框中显示数组值

Posted

技术标签:

【中文标题】如何在输入框中显示数组值【英文标题】:How to display array values in input box 【发布时间】:2021-10-06 18:48:08 【问题描述】:

我正在使用附加的下面的脚本来根据客户的需要显示多个输入框,因为名称相同,所以所有值都以数组形式保存在数据库中。一旦客户保存他的表格,我想在输入框中显示这些值。假设如果客户生成三个输入框并设置值1.abc 2.def 3.ghi,如何在页面加载时生成3个输入字段并将这些值放入其中?我是 javascript 新手,非常感谢任何帮助。这是我的代码:$value = "abc,def,ghi"

$(document).ready(function() 
    var wrapper         = $(".input_fields_wrap"); //Fields wrapper
    var add_button      = $(".add_field_button"); //Add button ID
   
    var x = 1; //initlal text box count
    $(add_button).click(function(e) //on add input button click
        
            x++; //text box increment
            $(wrapper).append('<div><input type="text" name="new_field_5[]" placeholder="Description"/><a href="#" class="remove_field">Remove</a></div>'); //add input box
        
    );
    $(wrapper).on("click",".remove_field", function(e) //user click on remove text
        e.preventDefault(); $(this).parent('div').remove(); x--;
    )
);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="input_fields_wrap">
    <button class="add_field_button">Add More Fields</button>
    <div><input type="text" name="new_field_5[]" placeholder="Description" value="<?php echo $value;?>"></div>
    
</div>

【问题讨论】:

【参考方案1】:

您可以创建一个对 php 文件的 Ajax 请求,该文件返回输入的所有值,然后使用 for in 循环将这些值分配给每个输入

【讨论】:

感谢您的快速响应,因为我是 jquery 和 ajax 的新手。你能给我一个示例代码来使用循环中的 ajax 检索这些值吗 这应该可以很好地了解该过程是如何进行的:js $.post('test.php', function(response) //Create a json Object const obj = JSON.parse(response); //Let's loop over every entry inside of the array for(let data in obj) //Append the data with the back-end values $('#results').append('&lt;input type="text" name="myName" value="'+obj[data]+'" &gt;'); ) 现在您可以在后端提供值:$array = [1,2,3]; echo json_encode($array);

以上是关于如何在输入框中显示数组值的主要内容,如果未能解决你的问题,请参考以下文章

MVC-如何根据在同一视图文本框中输入的值设置复选框的显示名称

用户输入值时如何从文本框中填充消息框?

如何在文本框中输入值后单击输入更改图像?

如何从输入框中显示 HTML

问题:将每次输入的信息保存在cookie中,再从cokie中取出值并显示在下拉框中。急需如何保存在cookie中...

如何在python的pandas数据框中输入单个值