我有一个页面,其中将随机创建一个动态创建的单选框组。我需要获取所有提交的单选框并将其存储在变量中。我不知道会有多少个单选按钮组。我需要动态分配它们,然后检索数据。我知道的一个信息是字段ID都将以“ chkpt_field _ ”开头
我知道第一步是获取所有字段的计数。
var count=0
jQuery('input[id*="chkpt_field_"]').change(function(){
count = jQuery('input[id*="chkpt_field_"]:checked').length
});
您从这里去哪里,我猜想是一个for循环,但是我不确定您将如何创建for循环来捕获所有与id匹配的字段
我当时正在考虑使用jQuery的每个函数来遍历表单提交中看到的每个检查字段,但这是行不通的……而我设置的方式只能设置一个值(如果它确实有效)。
jQuery('input[id*="chkpt_field_]').attr('checked', true).each(function(){
var id = (this).attr("id");
localStorage.setItem('field1', id);
});
我不是在找任何人为我工作,因为我需要学习它,但是如果有人有任何指示,技巧或窍门。我希望得到一些建议和指导。
已更新
var val1 = localStorage.getItem('chkpt_$field_name');
var itemval = jQuery('input[id='+val1+']').val();
jQuery("#"+val1).attr('checked', true);
jQuery(".signup_interest_form").submit(function(e){
jQuery('input[id*="chkpt_field_"]:checked').each(function() {
localStorage.setItem('chkpt_$field_name', jQuery('input[name="chkpt_$field_name"]:checked').attr('id'));
});
});
jQuery('input[name="chkpt_$field_name"]').change(function(e){
jQuery('input[name="$field_name"]').val(jQuery(e.currentTarget).data('value'));
jQuery('input[name="$field_name"]').trigger('change');
});
这将更新并将字段设置为选中,但是当我尝试提交表单时,没有数据传递,就好像根本没有设置表单数据一样。
我更新了更多内容,它检查了字段。但是值仍然不存在。提交时不发送任何信息
jQuery(document).ready(function(){
var val1 = localStorage.getItem('chkpt_$field_name');
var itemval = jQuery('input[id='+val1+']').val();
jQuery("#"+val1).prop('checked', 'checked').prop('checked', 'checked');
jQuery(".signup_interest_form").submit(function(e){
if (!jQuery('input[name="chkpt_$field_name"]:checked').val() )
{
jQuery('input[name="chkpt_$field_name"]').parents('.frm_toggle_container').toggle()
jQuery('input[name="chkpt_$field_name"]').parents('div.frm_section_heading').children('h3').css("color", "red")
return false;
} else {
jQuery('input[id*="chkpt_field_"]:checked').each(function() {
localStorage.setItem('chkpt_$field_name', jQuery('input[name="chkpt_$field_name"]:checked').attr('id'));
});
}
});
jQuery('input[name="chkpt_$field_name"]').change(function(e){
jQuery('input[name="$field_name"]').val(jQuery(e.currentTarget).data('value'));
jQuery('input[name="$field_name"]').trigger('change');
});
});
答案 0 :(得分:0)
我发现将其推入数组并检索该数组,然后分配由任务完成
这是我使用的代码。
var arr = [];
if(localStorage.getItem("array")!==null){
//test
var val1 = localStorage.getItem('array');
var stringArray = val1.split(',')
jQuery.each(stringArray, function(index,item){
jQuery("#"+item).attr('checked', true);
});
}
jQuery(".signup_interest_form").submit(function(e){
jQuery('input[id*="chkpt_field_"]:checked').each(function() {
arr.push(this.id);
});
localStorage.setItem('array', arr);
});
答案 1 :(得分:0)
事实证明,我只需要将请求作为Ajax请求发出,并防止页面重新加载,这样就解决了问题,而无需进行大量额外工作。