HTML 表单 - 提交所选 div 的 ID 数组



我有一个可以选择的div数组(更改点击背景颜色以表示对用户)。

我想要一种方法来提交所有这些div的id到我的应用程序,虽然不能看到一个"好"的方式这样做;目前,我唯一能做的就是有一个按钮,onclick触发一个javascript函数,获取id,并在POST中将它们发送回我的服务器。

是否有一种方法可以在使用div而不是复选框或多选择列表的表单上创建多个选择输入,或者更好的方法来做我正在尝试的事情?

假设您在用户'选择'div时添加了类selected:

var data = {};
$(".classOfDivs.selected").each(function(){
   data[$(this).prop('id')] = 'true';
}
$.ajax({
   url : 'ajaxPage.php',
   type : 'POST',
   dataType : 'text',
   cache: false,
   data: data,
   success : function(text){alert('Saved: '+text);},
   error: function(){alert('Did not reach server');}
});

根据需要使用success函数来处理返回的文本。dataType可改为htmlJSON等。参考.ajax()文档

为每个div设置一个隐藏的输入,所有div都具有相同的名称但具有不同的id。当单击div时,用id更新相应的隐藏输入。然后,当您通过标准表单POST提交时,所有这些值都可以通过您指定的名称获得。

由于这是一个应用程序,您可以做的是使用JQuery javascript库将所有内容存储在HTML5 localstorage中。

这里是如何一步一步地做:

    创建jquery数组点击
  1. ,获取div id并将其存储在数组中,并使用键/值对
  2. 如果再次点击,将其从数组中移除
  3. 有一些事件监听器,如"提交"按钮来存储数组的值到localstorage

这是我的一个jsfiddle,它正是你所说的:http://jsfiddle.net/CR47/bqfXN/1/

它稍微深入一些,但是jquery应该是你所需要的。

这比POST或ajax提交更好的原因是,因为你说这是一个应用程序,你将能够离线使用这种方法,而POST或ajax将需要连接到运行php的服务器。

var skinCare=[];                                       //the array
$('.skinCare').click(function(){                       //onclick
    var value = event.target.className.split(" ")[0];  //get classname, you would get id
    var index = skinCare.indexOf(value);               //gets where the location in 
                                                       //the array this code is
    if($(this).hasClass('selected')){                  //when a div is clicked it gets
        //$('.skinCare').removeClass('selected');      //the class "selected" and adds
        skinCare.splice(index, 1);                     //to array, then another click
    } else if($.inArray(value, skinCare) == -1){       //removes it from array
        skinCare.push(value);
    }
});
$('.submitbutton').click(function(){
    localStorage.setItem('Skin Care', JSON.stringify(skinCare));
});

最新更新