简体   繁体   English

javascript选择表格中的所有复选框

[英]javascript select all checkboxes in a table

I want to make a page that has a table of various webpages with checkboxes next to each.我想制作一个页面,其中包含一个包含各种网页的表格,每个网页旁边都有复选框。 I want the user to be able to select multiple sites then search the sites using a google bar.我希望用户能够选择多个站点,然后使用谷歌栏搜索这些站点。 I have a table where each cell has a form filled with checkboxes.我有一个表格,其中每个单元格都有一个填充了复选框的表格。 each cell has a checkall button that checks all the options in that cell.每个单元格都有一个 checkall 按钮,用于检查该单元格中的所有选项。 I would like to add a checkbox to select all the options on the page.我想添加一个复选框来选择页面上的所有选项。 (yes I could just leave this option out but I kind of want to know how to access all the boxes in the cells anyway so that I can search with google like I want.) here is basically what I have. (是的,我可以忽略这个选项,但我有点想知道如何访问单元格中的所有框,以便我可以像我想要的那样用谷歌搜索。)这基本上就是我所拥有的。 Its the section inside checkPage function that needs help at this point其 checkPage 函数内的部分此时需要帮助

<html>
<head>
<script type="text/javascript">
    function checkAll(checkname, bx) {
        for (i = 0; i < checkname.length; i++){
            checkname[i].checked = bx.checked? true:false;
        }
    }
    function checkPage(bx){


        var bxs = document.getElementByTagName ( "table" ).getElementsByTagName ( "link" ); 

        for(i = 0; i < bxs.length; i++){
            bxs[i].checked = bx.checked? true:false;
        }
    }
</script>


</head>
<body>
<input type="checkbox" name="pageCheck"  value="yes" onClick="checkPage(this)"><b>Check Page</b>
<table border="1" name ="table">

<tr>
    <td name ="list00">
        <form name ="list00">
            <input type="checkbox" name="Check_ctr" value="yes" onClick="checkAll(document.list00.link, this)"><b>Check All</b><dd>
            <input type="checkbox" name="link" value="something.com">something.com<dd>
            <input type="checkbox" name="link" value="something.com">something.com<dd>
        </form>
    </td>
    <td><form name ="list01">
            <input type="checkbox" name="Check_ctr" value="yes" onClick="checkAll(document.list01.link, this)"><b>Check All</b><dd>
            <input type="checkbox" name="link" value="something.com">something.com<dd>
            <input type="checkbox" name="link" value="something.com">something.com<dd>      
        </form></td>
</tr>
<tr>
    <td><form name ="list10">
            <input type="checkbox" name="Check_ctr" value="yes" onClick="checkAll(document.list10.link, this)"><b>Check All</b><dd>
            <input type="checkbox" name="link" value="something.com">something.com<dd>
            <input type="checkbox" name="link" value="something.com">something.com<dd>  
        </form></td>
    <td><form name ="list11">
            <input type="checkbox" name="Check_ctr" value="yes" onClick="checkAll(document.list11.link, this)"><b>Check All</b><dd>
            <input type="checkbox" name="link" value="something.com">something.com<dd>
            <input type="checkbox" name="link" value="something.com">something.com<dd>  
        </form></td>
</tr>
</table>

</body>
</html>
function checkAll(bx) {
  var cbs = document.getElementsByTagName('input');
  for(var i=0; i < cbs.length; i++) {
    if(cbs[i].type == 'checkbox') {
      cbs[i].checked = bx.checked;
    }
  }
}

Have that function be called from the onclick attribute of your checkbox to check all从复选框的 onclick 属性调用该函数以检查所有

<input type="checkbox" onclick="checkAll(this)">

Edit I misread your question a little, i see you have attempted it in your code.编辑我有点误读了你的问题,我看到你已经在你的代码中尝试过了。 the getElement s ByTagName has to be plural which you may have typo'd there and has to be a tag as specified by the answer above getElement s ByTagName 必须是复数,你可能在那里打错了,并且必须是上面答案指定的标签

Edit: Passing the master checkbox as a parameter would allow for toggling check/uncheck as suggested by vol7ron and has been modified in this answer appropriately.编辑:将主复选框作为参数传递将允许按照 vol7ron 的建议切换选中/取消选中,并已在此答案中进行了适当修改。

The question asks for all checkboxes on the page so this would suffice.该问题要求页面上的所有复选框,所以这就足够了。

However, providing control of which elements to look for checkboxes can be achieved in may ways, too many to go into detail but examples could be document.getElementById(id).getElementsByTagName if all checkboxes to be controlled are branched nodes from one element.但是,可以通过多种方式来控制要查找复选框的元素,方法太多了,无法详细介绍,但如果要控制的所有复选框都是来自一个元素的分支节点,则示例可以是 document.getElementById(id).getElementsByTagName。
Otherwise, you can iterate through a further tag name retrieval / custom class name retrieval to name a few.否则,您可以通过进一步的标签名称检索/自定义类名称检索进行迭代,仅举几例。

Example: http://jsfiddle.net/vol7ron/kMBcW/示例: http : //jsfiddle.net/vol7ron/kMBcW/

function checkPage(bx){                   
   for (var tbls=document.getElementsByTagName("table"), i=tbls.length; i--; )
      for (var bxs=tbls[i].getElementsByTagName("input"), j=bxs.length; j--; )
         if (bxs[j].type=="checkbox")
            bxs[j].checked = bx.checked;
}

using vanilla js使用香草js

checkAll = box => {
const checkboxes = document.getElementsByTagName('input')
for (const checkbox of checkboxes) {
  if (checkbox.type == 'checkbox')
    checkbox.checked = box.checked
}

put in your html放入你的html

<input type="checkbox" onclick="checkAll(this)">

Have you tried jQuery?你试过 jQuery 吗? It's becoming javascript standart library for DOM manipulation (stackoverflow using in too).它正在成为用于 DOM 操作的 javascript 标准库(stackoverflow 也使用 in)。

With it you could do $(':checkbox').prop('checked', true);有了它你可以做 $(':checkbox').prop('checked', true); to check every checkbox on the page(but you probably wan't to check then only in table).检查页面上的每个复选框(但您可能不想只在表格中检查)。

Well anyway start using jQuery, it will make your life easier and happier, and will save you a lot of time.好吧,无论如何开始使用 jQuery,它会让你的生活更轻松、更快乐,并且会为你节省大量时间。

... or even simpler if you want to flip all checkboxes in the corresponding form: ...或者更简单,如果你想翻转相应表单中的所有复选框:

function checkAll(bx){
    var form = bx.form;
    var ischecked = bx.checked;
    for (var i = 0; i < form.length; ++i) {
        if (form[i].type == 'checkbox') {
            form[i].checked = ischecked;
        }
    }
}

... ...

<input type="checkbox" onclick="checkAll(this)">

In my case, it helped me就我而言,它帮助了我

    <template>
  <div class="container">
    <ul class="list-group pt-1">
      <li class="list-group-item align-center">
        <button data-bs-toggle="collapse" data-bs-target="#dat_input" aria-expanded="false" aria-controls="income-expense" class="btn btn-sm border border-dark">
          Yana
        </button>
        <nuxt-link :to="`/admin/question/excel/create`" class="btn btn-success btn-sm">Excel orqali test qo'shish</nuxt-link>
        <span class="float-end">
          <button type="button" accesskey="1" class="btn btn-green btn-sm ">1 kunlik</button>
          <nuxt-link :to="`/admin/question`" class="btn btn-danger btn-sm " accesskey="b">Orqaga</nuxt-link>
        </span>
      </li>
      <li id="dat_input" class="list-group-item collapse">
        <p>Bu yerga endi biror nima qo`shiladi</p>
      </li>
    </ul>
    <div class="card mt-1">
      <table class="table table-sm">
        <thead class="table-dark table-sm">
        <tr>
          <th scope="col" class="text-center">
            <input class="form-check-input" type="checkbox" @click="selectAll(this, $event)">
          </th>
          <th scope="col" class="text-center"><i class="bi bi-sort-numeric-down-alt"></i></th>
          <th scope="col" class="text-center"><i class="bi bi-calendar3"></i></th>
          <th scope="col" class="float-left">Savol</th>
          <th scope="col" class="float-left">To'g'ri javob</th>
          <th scope="col" class="text-center"><i class="bi bi-alarm"></i></th>
          <th scope="col" class="text-center"><i class="bi bi-cash"></i></th>
          <th scope="col" class="text-center"><i class="bi bi-person-plus"></i></th>
          <th scope="col" style="width: 7%; text-align: center;"><i class="bi bi-diagram-3"></i></th>
        </tr>
        </thead>
        <tbody>
        <tr v-for="(question, id) in questions">
          <td width="1%" class="text-center align-middle">
            <input class="form-check-input" type="checkbox" @click="checkbox($event, question.id)">
          </td>
          <td width="3%" class="text-center align-middle" v-text="question.id"></td>
          <td width="8%" class="text-center  align-middle" v-text="question.create"></td>
          <td class="float-left  align-middle">{{ question.question }} <i class="bi bi-arrow-right"></i></td>
          <td class="float-left  align-middle" v-text="question.answer[0]"></td>
          <td width="1%" class="text-center align-middle" v-text="question.time"></td>
          <td width="1%" class="text-center align-middle"> {{ question.money }}</td>
          <td width="1%" class="text-center align-middle"> {{ question.rating }}</td>
          <td width="8%" class="text-center align-middle">
            <nuxt-link :to="`/admin/question/view/${question.id}`" class="btn btn-success btn-sm padingkichkina"><i class="bi bi-eye"></i></nuxt-link>
            <nuxt-link :to="`/admin/question/edit/${question.id}`" class="btn btn-primary btn-sm padingkichkina"><i class="bi bi-pencil"></i></nuxt-link>
            <a class="btn btn-outline-danger align-middle btn-sm padingkichkina" @click="deleteQuestion(question.id, question.question)"><i class="bi bi-trash"></i></a>
          </td>
        </tr>
        </tbody>
      </table>
    </div>
    <div class="card" v-if="next_page_url !== null">
      <button class="btn btn-success" @click="getPaginateTrade">
        Yana yuklash
      </button>
    </div>
  </div>
</template>
<script>
import Swal from 'sweetalert2'

export default {
  middleware: 'isAdmin',
  data() {
    return {
      questions: [],
      success: false,
      next_page_url: null,
      selected: [],
      isCheckAll: false,
    }
  },
  mounted() {
    this.$loading.show()
    this.getQuestions()
  },
  methods: {
    async getQuestions() {
      this.$axios.get('auth/questionsexcel')
        .then((res) => {
          this.questions = res.data.data.data;
          if (res.data.next_page_url !== null) {
            this.next_page_url = res.data.data.next_page_url
          }
        }).catch((error) => {
        this.has_error = true
        console.log(error.response.data.message)
      });
      this.$loading.hide();
    },
    async getPaginateTrade() {
      this.$axios.get(`${this.next_page_url}`)
        .then((res) => {
          if (res.data.next_page_url !== null) {
            this.next_page_url = res.data.data.next_page_url
            const questions = this.questions;
            this.questions = questions.concat(res.data.data.data)
          } else {
            this.SwalMixin("Boshqa savollar qolmadi", 'error')
          }
        }).catch((error) => {
        this.has_error = true
        console.log(error.response.data.message)
      });
    },
    checkbox(event, id) {
      this.isCheckAll = !this.isCheckAll;
      let array = this.selected;
      if (event.target.checked) {
        this.selected = array.concat(id);
      } else {
        this.selected = array.filter(item => item !== id);
      }
    },
    selectAll(bx, event) {
      var cbs = document.getElementsByTagName('input'), i = 0;
      if (event.target.checked) {
        this.selected = this.questions.map(item => item.id);
        for (i; i < cbs.length; i++) {
          if (cbs[i].type == 'checkbox') {
            cbs[i].checked = true;
          }
        }
      } else {
        this.selected = [];
        for (i; i < cbs.length; i++) {
          if (cbs[i].type == 'checkbox') {
            cbs[i].checked = false;
          }
        }
      }
    },
    deleteQuestion(id, name) {
      Swal.fire({
        title: "O'chirasizmi?",
        html: `<b>${name}</b> ni o'chirmoqchimisiz?`,
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#3085d6',
        cancelButtonColor: '#d33',
        confirmButtonText: "Ha o'chiraman",
        cancelButtonText: "Yo'q hozir emas"
      }).then((result) => {
        if (result.isConfirmed) {
          this.$axios.post('auth/deleteQuestion', {
            id: id
          }).then((response) => {
            this.SwalMixin(response.data.data.message)
            this.getQuestions()
          }).catch((error) => {
            this.SwalMixin(error.response.data.message, 'error')
          });
        }
      })
    },
  }
}
</script>

标签名称是开始 html 标签的位,例如<input所以.getElementsByTagName ( "link" )应该是.getElementsByTagName ( "input" )如果你只想要name='link'那么if(bxs.name =="link") { ... change the checked }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM