jeudi 31 mars 2016

detecting class changes in Bootstrap Switch Jquery (converting working checkbox JS to button js)

I am trying to convert a piece of JQuery that changes the class of a tr when checked to a piece of JQuery that changes the class of a tr when a button gets a class called "active". I am a JQuery/Javascript newbie and I am at a loss.

For those who have suggested it's a duplicate, I have tried to detect class and failed (updated code below).

ORIGINAL CODE (THAT WORKS)

javascript:
  var $input_class = $('.addCheckbox');
  function setClass() {
    var tr = $(this).closest( "tr" );
    if ($(this).prop('checked') == true){
      tr.addClass( "highlight" );
    }
    else{
      tr.removeClass( "highlight" );
    }
  }
  for(var i=0; i<$input_class.length; i++) {
    $input_class[i].onclick = setClass;
  }

MY HORRIBLE TRY

javascript:
  var $input_class = $('.btn-group .btn-toggle .btn');
  function setClass() {
    var tr = $(this).closest( "tr" );
    if ($(this).prop('.btn-success .active')){
      tr.addClass( "highlight" );
    }
    else{
      tr.removeClass( "highlight" );
    }
  }
  for(var i=0; i<$input_class.length; i++) {
    $input_class[i].onclick = setClass;
  }

I am using the Bootstrap Switch Plugin which converts checkboxes to toggles http://ift.tt/11UUAbz

The converted html looks like this:

<tr>  
  <td width="15px"><input class="addCheckbox" type="checkbox" value="true" style="display: none;">
    <div class="btn-group btn-toggle" style="white-space: nowrap;">
      <button class="btn active btn-success btn-md" style="float: none; display: inline-block; margin-right: 0px;">YES</button>
      <button class="btn btn-default  btn-md" style="float: none; display: inline-block; margin-left: 0px;">&nbsp;&nbsp;&nbsp;</button>
    </div>
  </td>
  <td width="85px">May 2016</td><td class="restaurant-name">
      Joe's Crab Shack
  </td>
  <td class="text-center">
    #my table info
  </td>
</tr>

UPDATE!!! As per 'duplicate' suggestions.

After looking through this question (which was very helpful), I have changed my code to this, and I still can't get it to work. I am wondering if it is having trouble finding the exact input class? Because the plugin converts the checkbox to html, I can't (or don't know how) set specific names or ids for the buttons.

 javascript:
      var $input_class = $('.addCheckbox .btn');
      var tr = $(this).closest( "tr" );
      function checkForChanges()
      {
        if ($('.btn').hasClass('btn-success')) 
          tr.addClass( "highlight" );

        else 
          tr.removeClass( "highlight" );
      }
      for(var i=0; i<$input_class.length; i++) {
        $input_class[i].onclick = checkForChanges;
      }




Aucun commentaire:

Enregistrer un commentaire