我遇到一个小问题,当我通过JS提交表单时,我想从select元素中获取所有值...我的意思是像每个用户一样,select元素的值。
<?php foreach($users as $user) : ?>
<div>
<p><?php echo $user['user_first'].' '.$user['user_last']; ?></p>
<form action="" method="post">
<select name="user-state">
<option value="Je na hodine">Je na hodine</option>
<option value="Chýba">Chýba</option>
<option value="Meškanie">Meškanie</option>
</select>
<input type="input" name="user" value="">
</form>
</div>
<?php endforeach; ?>
JS:
document.getElementById('saveBtn').addEventListener('click', function(){
document.getElementById('dochadzka-form').submit(); });
答案 0 :(得分:0)
如果您希望所有数据都在一个提交中,则需要将所有输入包装在一个表单中。要在提交后以PHP数组形式获取数据,您应将name
属性的格式设置为name="user-state[]"
。
类似的事情应该可以解决(未尝):
<form action="" method="post">
<?php foreach($users as $user) : ?>
<fieldset>
<legend><?php echo $user['user_first'].' '.$user['user_last'] ?></legend>
<input name="user[]" value="<?php echo $user['id'] ?>" type="hidden">
<select name="user-state[]">
<option value="Je na hodine">Je na hodine</option>
<option value="Chýba">Chýba</option>
<option value="Meškanie">Meškanie</option>
</select>
</fieldset>
<?php endforeach; ?>
<button type="submit">Submit</button>
</form>
说明其工作原理的示例:
// This is only needed to show the form data in this example.
// If you only need the data in PHP you don't need any JavaScript.
var form = document.getElementById("dochadzka-form");
form.addEventListener("submit", function(event) {
var data = new URLSearchParams(new FormData(form)).toString();
console.log(data);
event.preventDefault(event);
});
<form action="" method="post" id="dochadzka-form">
<fieldset>
<legend>User 1</legend>
<input name="user[]" value="1" type="hidden">
<select name="user-state[]">
<option value="Je na hodine">Je na hodine</option>
<option value="Chýba">Chýba</option>
<option value="Meškanie">Meškanie</option>
</select>
</fieldset>
<fieldset>
<legend>User 2</legend>
<input name="user[]" value="2" type="hidden">
<select name="user-state[]">
<option value="Je na hodine">Je na hodine</option>
<option value="Chýba">Chýba</option>
<option value="Meškanie">Meškanie</option>
</select>
</fieldset>
<br>
<button type="submit">Submit</button> to show the form data
</form>
答案 1 :(得分:0)
<form action="" method="post">
<?php $i = 0; foreach($users as $user) : ?>
<div>
<p><?php echo $user['user_first'].' '.$user['user_last']; ?></p>
<select name="user-state<?= $i?>">
<option value="Je na hodine">Je na hodine</option>
<option value="Chýba">Chýba</option>
<option value="Meškanie">Meškanie</option>
</select>
<input type="input" name="user<?= $i?>" value="">
</div>
<?php $i++; endforeach; ?>
</form>