jquery - 检查是否缺少元素 ID
问题描述
我有一个带有按钮的动态表单,可以在分配诸如Ingredient[1]
、Ingredient[2]
、之类的 id 时添加和删除行Ingredient[3]
。但是我想找出一种方法来检查是否在某个地方被删除,例如如果Ingredient[2]
被删除,我希望下一行被添加Ingredient[2]
,然后因为Ingredient[3]
已经存在下一行应该是Ingredient[4]
。
这是我的 addRow 函数。
var x = 1;
function addRow() {
var tr = '<tr>' +
'<td>' +
'<select name="ingredient[' + x + ']" id="ingredient[' + x + ']" class="form-control>' +
'@foreach($ingrListRecipe as $ingrListRecipe)' +
'<option value="{{ $ingrListRecipe->id }}">{{ $ingrListRecipe->name}}</option>' +
'@endforeach' +
'</select>' +
'</td>' +
'<td><input type="text" name="quantity[' + x + ']" class="form-control"></td>' +
'<td><select name="measurement[' + x + ']" class="form-control">' +
'<option value="Grams">Grams</option>' +
'<option value="Tbsp">Tbsp</option>' +
'<option value="Mililitres">ML</option>' +
'</select>' +
'</td>' +
'<td style="text-align: center"><a href="#" class="btn btn-danger remove">Remove Row</a></td>' +
'</tr>';
$('tbody').append(tr);
x++;
};
这是我的 removeRow 函数 if 语句是我用来查看存在的东西
$(document).on('click', ".remove", function() {
$(this).parent().parent().remove();
i = 1
if (document.getElementById('ingredient[' + i + ']')) {
alert('Element Present ' + ' I= ' + i + ' X= ' + x);
i++;
} else {
x = i;
alert('Element Not Present ' + ' I= ' + i + ' X= ' + x);
}
});
更新:通过更改为成分 [] 集合并在添加中使用 foreach 来解决。
function addRow(){
var tr = '<tr>' +
'<td>' +
'<select name="ingredient[]" id="ingredient[]" class="form-control>' +
'@foreach($ingrListRecipe as $ingrListRecipe)'+
'<option value="{{ $ingrListRecipe->id }}">{{ $ingrListRecipe->name}}</option>'+
'@endforeach'+
'</select>'+
'</td>' +
'<td><input type="text" name="quantity[]" class="form-control"></td>'+
'<td><select name="measurement[]" class="form-control">'+
'<option value="Grams">Grams</option>'+
'<option value="Tbsp">Tbsp</option>'+
'<option value="Mililitres">ML</option>'+
'</select>'+
'</td>'+
'<td style="text-align: center"><a href="#" class="btn btn-danger remove">Remove Row</a></td>'+
'</tr>';
$('tbody').append(tr);
};
foreach($ingredient as $key => $no)
{
$reIng = new RecipeIngredient();
$reIng->recipeid = $recipe->id;
$reIng->ingredientid = $no;
$reIng->quantity = $quantity[$key];
$reIng->measurement = $measurement[$key];
$reIng->save();
}
return redirect()->back();
return redirect('/home');
}
解决方案
我将展示一个更新元素id
s的函数。select
document.querySelectorAll('[id^="ingredient["]').forEach((select, index) => {
select.id = `ingredient[${index+1}]`;
})
推荐阅读
- javascript - 试图让firebase实时数据库在反应中工作,这个代码段有什么问题?
- javascript - 在 PHP 和 JavaScript 中格式化货币
- android - 第二次未调用 RxJava Observable onNext
- c# - 使用现有单词 .doc 和 .net core 查找和替换
- regression - 如何解释回归变量的后验概率?
- regex - 用于从特定字母和零个或多个元音中查找单词的正则表达式组合
- powershell - 使用 ANSI / VT100 代码在 PowerShell 控制台中输出彩色文本
- julia - 将数组转换为列表-Julia
- android - SearchView 聚焦时是否有事件?
- c# - CefSharp 网页元素点击