用户使用javascript生成输入字段,如果验证失败,如何在输入字段中填充其数据

时间:2014-09-10 22:09:07

标签: javascript php html forms validation

我有一个输入字段部分,需要填写一个字段,但是如果他们想要添加更多字段,则会点击+按钮并生成新的输入字段。他们也可以点击 - 按钮删除它。如何对这些用户生成的输入字段执行验证?当我点击表单上的提交按钮时,用户生成的字段消失,因此我无法重新显示他们填写的数据,以便他们可以看到他们做错了什么并进行了更改。

<div id="pick_style">
<label for="pick_up_location">Pick Up Location(s)</label>
<input type="text" name="pick_up_location_1" 
value="<?php if (isset($_POST['pick_up_location_1'])) 
{ echo $_POST['pick_up_location_1']; } ?>"list="pick_up_location" />
<datalist name="pick_up_location" id="pick_up_location">
<?php while($row = mysqli_fetch_array($pickup_location_initial)){ ?>
<option value="<?php echo $row['store_city'] . ',' 
. ' ' . $row['store_state'] . ' ' .$row['store_num']; ?>">
<?php
}
?>
</datalist>

<input type="button" id="add_pickup()" onClick="add_pickup()" value="+" />
</div>

这是必需的初始提取位置,如果验证失败并且值为= isset $ _POST变量,则很容易显示给用户。但是当用户想要添加额外的提取位置时,他们会点击+按钮触发此代码:

var p = 1; 
function add_pickup(){

if (p <= 4){

p++; 

var div = document.createElement('div'); 
div.innerHTML = '<label for="pick_up_location"></label>
<input type="text"   name="pick_up_location_'+p+'" list="pick_up_location" />
<datalist name="pick_up_location" id="pick_up_location">
<?php while($row = mysqli_fetch_array($resultpickup)){ ?>
<option value="<?php echo $row['store_city'] . ',' . ' ' .
$row['store_state'] . ' ' .   $row['store_num']; ?>"><?php } ?></datalist>
<input type="button" id="add_pickup()" onClick="add_pickup()" value="+" />
<input type="button" onClick="removePick(this)" value="-" />';
document.getElementById('pick_style').appendChild(div);
}
 }

function removePick(div){

document.getElementById('pick_style').removeChild( div.parentNode )
p--; 

}

如果验证失败,如果他们填写2,3,4或5个字段,我将如何重新显示用户输入数据?我想通过向他们展示他们之前放入的内容来轻松修复它们?

1 个答案:

答案 0 :(得分:0)

只需在服务器端迭代pick_up_location_1, ..., pick_up_location_4并使用-(减号)按钮创建HTML:

<div id="pick_style">
<?php for ($i = 1; $i < 5; $i++) { ?>
<?php $key = 'pick_up_location_' + $i; ?>
<?php if (isset($_POST[$key])) { ?>
  <label for="pick_up_location">Pick Up Location(s)</label>
  <input type="text" name="<?php echo $key; ?>"
    value="<?php if (isset($_POST[$key])) { echo $_POST[$key]; } ?>" list="<?php echo $key; ?>" />
  <datalist name="<?php echo $key; ?>" id="<?php echo $key; ?>">
  <?php while ($row = mysqli_fetch_array($pickup_location_initial)) { ?>
  <option value="<?php echo $row['store_city'] . ',' . ' ' . $row['store_state'] . ' ' . $row['store_num']; ?>">
  <?php } ?>
</datalist>
<input type="button" onClick="removePick(this)" value="-" />
<?php } /* if */ ?>
<?php } /* for */ ?>
<input type="button" id="add_pickup()" onClick="add_pickup()" value="+" />
</div>