【发布时间】:2020-08-20 18:01:57
【问题描述】:
我有一个带有动态字段和动态行的表格的表格。所以最初表格包含一行有两个字段,当我填写它们并单击 Enter 时,jquery 函数将在下面创建一个新行。
到了提交表单的时候,我正在检查是否有任何空字段,如果有则显示错误但问题出在此处,它会清除所有字段。提交时如何保留它们?
他是 HTML:
<form action="" method="post">
<button type="submit" class="btn" name="add_device">Add devices</button>
<?php foreach ($dev_type_results as $row) {
} ?>
<table id="ble_table" class="table table-bordered table-striped" cellspacing="0" width="100%">
<tr>
<th>No.</th>
<th>Serial no.</th>
<th>IMEI</th>
</tr>
<tr>
<td>1</td>
<td><input type="text" class="inputs" name="serial_no[]" value="<?php if (isset($_POST['serial_no'])) { echo htmlspecialchars($_POST['serial_no']);} ?>" /></td>
<td><input type="text" class="inputs lst" name="imei[]" value="<?php if (isset($_POST['imei'])) { echo htmlspecialchars($_POST['imei']); } ?>" /></td>
</tr>
</table>
</form>
jquery函数:
var i = $('table tr').length;
$(document).on('keyup', '.lst', function(e) {
var code = (e.keyCode ? e.keyCode : e.which);
if (code == 13) {
html = '<tr>';
html += '<td>' + i + '</td>';
<?php foreach ($dev_type_results as $row) {
}
html += '<td><input type="text" class="inputs" name="serial_no[]' + i + '" value="<?php if (isset($_POST['serial_no'])) { echo htmlspecialchars($_POST['serial_no']);} ?>"/></td>';
html += '<td><input type="text" class="inputs lst" name="imei[]' + i + '" value="<?php if (isset($_POST['imei'])) { echo htmlspecialchars($_POST['imei']);} ?>"/></td>';
html += '</tr>';
$('table').append(html);
$(this).focus().select();
i++;
}
});
$(document).on('keydown', '.inputs', function(e) {
var code = (e.keyCode ? e.keyCode : e.which);
if (code == 13) {
var index = $('.inputs').index(this) + 1;
$('.inputs').eq(index).focus();
event.preventDefault();
}
});
为简洁起见,我将在下面发布我验证的 PHP 代码:
if (count(array_filter($_POST['serial_no'])) < count($_POST['imei'])) {
array_push($errors, "Found empty field in Serial no. column");
}else{
//call function to post to database
}
我已经尝试过使用全局变量,但它不起作用。我还能尝试什么?
【问题讨论】:
-
首先,如果您在同一页面中处理表单,表单必须具有此操作:
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" >它会将表单发送到“self”,即您进入的页面的 url。我不知道它是否适用于空操作。 -
一个有用的快捷方式:
<?php echo $variable; ?>可以替换为<?=$variable;?>它做同样的事情! :-) -
$dev_type_results的值是多少?它从未在此代码中的任何位置分配。 -
我假设您要创建 N 行,具体取决于从数据库返回的记录数。但是如果没有看到问题所涉及的部分,就很难提出要解决的问题。如果代码太长,或者很难准备这篇文章,你可以粘贴到jsfiddle.net session,并在这里分享链接,这样我们就可以看到整个事情了。如果 php 代码没有在那里运行,请不要担心,这只是为了阅读代码。谢谢
-
是的,我知道,但我看到了一些混乱,事实上,上面的 sn-p 中缺少从 php 生成 html 的部分(请编辑您的问题,以便其他用户可以看到如果这篇文章可以帮助他们或没有)。
if ($row['serial_or_imei'] === null || 'both')这将不起作用“两者”将始终运行,因为它将评估为true。你的意思是if ($row['serial_or_imei'] === null || $row['serial_or_imei'] === 'both')?。另外,array_filter php函数期望返回什么?你能写出那段代码背后的概念吗?还有<br/> not </br>!
标签: php html jquery forms form-submit