我有一系列从sqlite数据库创建的单选按钮
我使用jquery each函数来遍历无线电组。对于每个组,如果有选中的项,我将向数据库插入一条记录,如下所示-
$('input:radio:checked').each(function(Index) {
Index=Index+1; // to start at 1 not 0
var kind_id = $('input:radio[name='+Index+']:checked').val();
// get value of the checked radio button which corresponds to 'kind' index in the database
var cat_id = $('input[name='+Index+']:radio:checked').attr('data-id');
// get the radio group name which corresponds to the category index in the database and, in turn, is the value of Index
tx.executeSql( 'INSERT INTO quotelink(ql_quote_id,ql_cat_id,ql_kind_id) Values (last_insert_rowid(),?,?)', [cat_id,kind_id],
nullHandler,errorHandler ,
[],nullHandler,errorHandler);
}); //end each function
在我删除一个类别之前,这个工作很好。例如,如果我在数据库中有类别1、3、4、5(我已经删除了2个)。当我触发该函数时,像预期的那样插入了四行,但是cat_id列是1、undefined、3,4,而不是1,3,4,5。
。当Index=2时,它在寻找一个不存在的元素。我不知道下一步该做什么。
有点复杂-希望我已经解释清楚了,任何帮助都非常感谢
"undefined"的值是正确的,因为你试图访问一个不存在的单选输入,所以jquery/js将返回"undefined"。
我认为在循环中增加索引变量是行不通的。为什么不在循环中使用$(this)对象来访问当前选中的无线电输入的所需属性呢?
试试这个:
$('input:radio:checked').each(function(Index) {
//Index=Index+1; // to start at 1 not 0
var currentRadio = $(this);
//var kind_id = $('input:radio[name='+Index+']:checked').val();
var kind_id = currentRadio.val();
// get value of the checked radio button which corresponds to 'kind'
// index in the database
//var cat_id = $('input[name='+Index+']:radio:checked').attr('data-id');
var cat_id = currentRadio.attr('data-id');
// get the radio group name which corresponds to the category index in the database
// and, //in turn, is the value of Index
//... insert into database
}