我有输入字段的html格式,并且可以使用javascript函数按需创建其他输入字段。这是完美的脚本:
<input id="myField0" name="myField[]" value="<?php echo isset($_POST['myField'][0]) ? $_POST['myField'][0] : '' ?>" class="awesomplete" list="myList" size="32"/><br>
<input id="myField1" name="myField[]" value="<?php echo isset($_POST['myField'][1]) ? $_POST['myField'][1] : '' ?>" class="awesomplete" list="myList" size="32"/><br>
<input id="myField2" name="myField[]" value="<?php echo isset($_POST['myField'][2]) ? $_POST['myField'][2] : '' ?>" class="awesomplete" list="myList" size="32"/><br>
<input id="myField3" name="myField[]" value="<?php echo isset($_POST['myField'][3]) ? $_POST['myField'][3] : '' ?>" class="awesomplete" list="myList" size="32"/><br>
<script>
// Start function for additional input fields
var counter = 5;
var limit = 15;
function addInput(divName){
if (counter == limit) {
alert("You have reached the limit of " + counter + " inputs");
} else {
// Create new div
var newdiv = document.createElement('div');
newdiv.innerHTML = '<br><input type="text" id="myField' + counter + '" name="myField[]" class="awesomplete" list="myList" size="32"/>';
document.getElementById(divName).appendChild(newdiv);
// Re instantiate Awesomplete
new Awesomplete(newdiv.querySelector('input'), { list: document.querySelector('#myList') });
// Set counter
counter++;
}
}
// End function for additional input fields
</script>
<div id="dynamicInput">
<b></b><input type="text" id="myField4" name="myField[]" value="<?php echo isset($_POST['myField'][4]) ? $_POST['myField'][4] : '' ?>" class="awesomplete" list="myList" size="32"/>
</div>
<input type="button" id="additional_inputfield" value="Additional input field" onClick="addInput('dynamicInput');">
现在,我希望在发送表单后将输入的数据保留在输入字段中。这在预先存在的输入字段中很好用,但是,不是在额外创建的输入字段中,因为我不能在我的javascript函数中使用php。是否有任何简单的解决方案可以在所有字段中保留输入的值?
答案 0 :(得分:0)
有许多可能的解决方案,从呈现表单服务器端到使用javascript重建它,基于从php转储到脚本标记中的一些数据。
由于你的javascript似乎只是dom操作,而不是数据支持(angularjs,vuejs等),所以第一个选项可能是最简单的:
$inputCount = 4; //default
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
$inputCount = count($_POST['myfield']); //set count to number of posted fields
}
//create as many inputs as required.
for($i=0; $i<=$inputCount; $i++):?>
<input id="myField<?= $i; ?>" name="myField[]" value="<?= isset($_POST['myField'][$i]) ? $_POST['myField'][$i] : ''; ?>" class="awesomplete" list="myList" size="32"/><br>
<?php endfor;>
<script>
// Start function for additional input fields
var counter = <?=$inputCount +1;?>;
//the rest of your code
注意我已经使用php短回声标记<?=
代替<?php echo
作为个人偏好,它们在功能上是相同的