javascript - 允许用户插入两列数据集的更好方法是什么?
问题描述
我想要一种有效的方法来允许我的网站用户将歌曲列表上传到他们的个人资料页面。目前,我正在使用<textarea>
需要特定格式的表单。歌曲列表的格式必须如下:
Some Band Name,Name of the song
Some other Band,Name of that song
...etc
我的网站会查找逗号,这会告诉网站在每一行中,逗号之前是艺术家姓名,逗号之后是歌曲名称。但对于像这样的歌曲来说,这是一个问题:
Neil Diamond,Girl, You'll be a Woman Soon
歌曲标题中的第二个逗号搞砸了网站逻辑,实际上插入到他们个人资料中的是:
Neil Diamond, "Girl"
允许我的用户将(有时数百)歌曲列表添加到他们的个人资料中的更好方法是什么?
编辑:为了更清楚,我正在寻找一种方法,让我网站上的前端登录用户能够通过 HTML 表单提交一组两列的日期。然后,该数据将通过表单提交到我的 Wordpress 后端,并且每个行项目将作为自定义帖子添加到 Wordpress 中。我已经弄清楚了所有后端逻辑,但我试图找到一种更好的方法来允许用户添加这些数据,而不是仅仅使用<textarea>
输入框并希望他们的所有数据都符合所需的格式条件。
解决方案
您可以使用两个textarea
,一个是艺术家,另一个是歌曲。
您可以使用另一个分隔符(|
而不是,
不太常见的是歌曲标题)。
当用户单击“加号”按钮时,您还可以使用 Javascript 更“动态地”添加两个输入。您将获得 POST 数据作为两个数组:
<form id="form" method="post" action="https://postman-echo.com/post">
<div>
<input name="songs[name][]" value="Girld, You'll be a Woman soon">
<input name="songs[artist][]" value="Neil Diamond">
</div>
</form>
<button onclick="addMore()">Add one more song</button>
<button onclick="submit()">Submit form</button>
<script>
/**
* Add one more song inputs
*/
function addMore() {
// Create a div
const div = document.createElement("div");
// Create the name input
const name = document.createElement("input");
name.setAttribute("type", "text");
name.setAttribute("name", "songs[name][]");
name.setAttribute("placeholder", "Name");
// Create the artist input
const artist = document.createElement("input");
artist.setAttribute("type", "text");
artist.setAttribute("name", "songs[artist][]");
artist.setAttribute("placeholder", "Artist");
// Add the inputs to the div
div.appendChild(name);
div.appendChild(artist);
// Append the div to the form
document.getElementById("form").appendChild(div);
}
/**
* Submit the form
*/
function submit() {
document.getElementById("form").submit();
}
</script>
推荐阅读
- python - 如何在排列列表中找到一个键?
- java - 如何通过 gson 将 json 反序列化为嵌套的自定义地图?
- javascript - 根据关键字对象返回对象数组
- javascript - 使用 htmx 和 tinymce 时出现错误列表
- algorithm - 插入排序和线性搜索同时VS插入排序和二进制搜索?
- javascript - 在 getServerSideProps() 中使用 NextAuth 挂钩 useSession()
- reactjs - 我们可以将数据表导出到 Excel 而不是 CSV(React bootstrap table2)吗?
- python - 没有这样的文件或目录:'/elrondsdk/vmtools/mandos-test'
- ruby-on-rails - 即使使用 redis,ActionCable 也会返回 0 或 nil
- python - 测试数字并仅返回右侧有一位数字的小数