سؤال

I have this table form:

<?php while($resulat = $sql_adherent->fetch_object()): ?>
<tr>
   <td class="highlight">
       <div class="important"></div>
           <a href="#"><?php echo $resulat->nom_compte; ?></a>
   </td>                                 
   <td class="hidden-xs"><?php echo $resulat->cin; ?></td>
   <td class="hidden-xs"><?php echo $resulat->sexe; ?></td>
   <td><?php echo $resulat->date_naissance; ?></td>
   <td></td>
   <td><?php echo $resulat->date_effet; ?></td>
   <td><?php echo $resulat->date_expiration; ?></td>
   <td><a href="#" class="btn default btn-xs red-stripe" id="validate">Validate</a></td>
 </tr>                             

I Want to change "Validate" to "Validated" onclick the id="validate" and I'm using live() function to do this but it's not working

Here is the code i'm using:

$("#validate").live('click', function(e){
    e.preventDefault();

    $(this).addClass('green-stripe');
    $(this).removeClass('red-stripe');
    $(this).html('Validated');    
  });

I tried to change the code to toggle "Validate" & "Validated" using this code,

$("#validate").toggle(function(e){
    e.preventDefault();  

    $(this).addClass('green-stripe');
    $(this).removeClass('red-stripe');
    $(this).html('Validated');    
  }, function(){
     $(this).addClass('red-stripe');
     $(this).removeClass('green-stripe');
     $(this).html('Validate');
});

but also doesn't work.. I know I did something wrong but can"t find the mistake..

هل كانت مفيدة؟

المحلول

live is deprecated, so don't try to use it anymore, use on instead.

toggle event is deprecated anche can't be used anymore as click handler, in this case you can check if your element have a class as identifying element.

Ref:

Note: This method signature was deprecated in jQuery 1.8 and removed in jQuery 1.9. jQuery also provides an animation method named .toggle() that toggles the visibility of elements. Whether the animation or the event method is fired depends on the set of arguments passed.

To switch the classes you can use toggleClass with multiple classes.

Code:

$("#validate").on('click', function (e) {
    e.preventDefault();

    $(this).toggleClass('red-stripe green-stripe');

    ($(this).hasClass('red-stripe')) ? $(this).html('Validate') : $(this).html('Validated');
});

Demo: http://jsfiddle.net/IrvinDominin/VyD6x/

نصائح أخرى

.live is deprecated. Change your js to this.

$(document).on('click', '#validate', function(e){
e.preventDefault();

$(this).addClass('green-stripe');
$(this).removeClass('red-stripe');
$(this).html('Validated');    
});

Read Live is Deprecated

.toggle() deprecated: 1.8, removed: 1.9

use .on()

Read Event Delegation

Use .toggleClass()

$(document).on('click', '#validate', function(e){
   $(this).toggleClass('green-stripe red-stripe');
});
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top