如何获取页面上每个复选框的位置或索引

时间:2014-05-10 18:20:40

标签: jquery asp.net

您好我正在尝试获取页面上所选复选框的索引。我已经看到很多例子将每个新添加的元素的索引都添加到数组中,但我想获得复选框在页面上的位置索引。我一直在尝试下面的代码:

      $("#saveBtn").click(function () {
      var selectedItems = $("input[name='selectedCourses']:checked");

        if (selectedItems.length > 0) {
            for (var i = 0; i < selectedItems.length; i++)
                alert("Selected Text: " + selectedItems.eq(i).val() + " Selected Index: " + selectedItems[i].valueOf() + selectedItems.index(i).val());



     };


  });

我想在我的循环中做这样的事情:

 var positionOfCheckedBoc= selectedItems.index(i).val());

我能够做到这样的事情:

 $("#saveBtn").click(function () {
         var checked = [];


         $("input[name='selectedCourses']:checked").each(function (i) {

             checked.push(parseInt($(this).val()));

             alert("The index is " + i + " and the value is " + $(this).val());
         });

      });

但是索引是从0到选择的项目数而不是页面上的索引或位置。

请帮助我获取所选项目的位置 感谢。

5 个答案:

答案 0 :(得分:0)

试试这个和它的作品,我认为这足以帮助你

   $("#saveBtn").on("click",function(){
        var index = 0;
     $('.selectedCourses').each(function() {
            if (this.checked) {
                alert(index);
            }
            index++;
        });
    });

此处输出的代码为:http://jsfiddle.net/bvUND/64/

答案 1 :(得分:0)

您需要遍历所有复选框,而不仅仅是已选中的复选框

 $("#saveBtn").click(function () {
         var checked = [];


     $("input[name='selectedCourses']").each(function (i) {
         if(this.checked){
             checked.push(parseInt($(this).val()));
             alert("The index is " + i + " and the value is " + $(this).val());
         }
         });

      }); 

Wroking DEMO

答案 2 :(得分:0)

试试这个:

Demo

你可以循环元素。

答案 3 :(得分:0)

试试这个:

$(document).on('change', 'input', function () {
    var collection = $('body *');
    var i = $(this);
    var index = collection.index(i);
    alert("Index of item on page is :"+index);
});

演示:http://jsfiddle.net/lotusgodkk/GCu2D/99/ 它将为您提供正文中所有元素之间当前输入的索引。这是你想要的吗?你可以修改它以获得位置。

答案 4 :(得分:0)

重新定义匹配的元素集

元素的索引是相对于它在匹配的元素集中的位置。

在您的示例中,匹配的集合是已选中名称为“selectedCourses”的输入元素。然而,你暗示你想要它在页面上的索引或位置,但相对于什么?

  • 是否选中了名为“selectedCourses”的所有输入?
  • 所有输入无论名称如何?
  • 所有表单元素即使不是输入元素?
  • 所有DOM节点?

扩展您的查询并使用逻辑来获取更大集合中所需元素的索引

此示例假设您希望命名,检查输入的索引相对于页面上的所有输入:

$("#saveBtn").click(function () {
    var checked = [];
    $("input").each(function (i) {
        if ($(this).is(":checked") && $(this).attr("name") == "selectedCourses") {
            checked.push(parseInt($(this).val()));
            alert("The index is " + i + " and the value is " + $(this).val());
        }
    });
});