Skip to content Skip to sidebar Skip to footer

How Can I Get Element With Checked Label In Tag?

In javascipt/jquery How can I get checked element name. These are in table. And I have to reach and detect label of checked checkbox in td tag. $.each(value.Value, function (_, Ob

Solution 1:

IDs must be unique, you should use classes instead. You can store the values in an array using map method.

var listCluster = $('table td').has('input[type=checkbox]:checked').map(function(){
    return this.textContent || this.innerText;
    // return $.trim( $(this).text() );
}).get();

http://jsfiddle.net/SUHsT/


Solution 2:

1) Ids MUST be Unique. You can not have multiple elements with the same ID.

So with that out of the way, lets assume you have the following DOM:

<table id="myTable">
  <tr>
   <td id="clusterList1">Cluster1<input type="checkbox" checked="checked"></td>
   <td id="clusterList2">Cluster2<input type="checkbox" checked="checked"></td>
   <td id="clusterList3">Cluster3<input type="checkbox" checked="checked"></td></tr></table>

And, given that your example does not include name attributes, I am assuming that when you say "name" you mean "the text just before the input field". Then your jquery would look as follows:

     ListCluster = []
     $('table#myTable tr td input[type=checkbox]').on('change', function(){
           if($(this).attr('checked')=='checked'){
              if(ListCluster.indexOf($(this).parent().text()==-1){
                 ListCluster.push($(this).parent().text());
              }
           } else if(ListCluster.indexOf($(this).parent().text()>=-1){
              ListCluster.splice($(this).parent().text(), 1);
           }
      }

Here's how it works.

You initialize an array ListCluster. You then add an on change handler to all of the checkboxes at your desired level of nesting. The reason to use a change handler rather then a click handler, is that a change handler will allow you to handle a value change based on spacebar being pressed after tabbing into the checkbox, while a click event would not pick this up.

Inside the change handler, $(this) refers to the checkbox changed, while .parent() reaches up one level to get its wrapping td.

.text() will get a DOMElements text discarding all HTML.

indexOf() will return the first index where a value is found or -1 if it is never found thus comparing indexOf to -1 is equivalent to asking "is this item present?"

.push() is a function which adds an element to the end of an array, while .splice(x, y) will remove y elements starting at the index of x.


Solution 3:

$('td input:checked').parent().text();

btw ids must be unique.


Post a Comment for "How Can I Get Element With Checked Label In Tag?"