0

我有简单的评论表格。我把 char-counter 。当我创建新评论时一切正常。当我尝试编辑评论时,字符计数器不起作用。我尝试了 Live(),但结果是一样的。编辑页面中的其他 Js 工作正常,只是这个 keyup 功能死了。我试图发出警报以查看 keyup 是否有效,但没有回应。这是我的代码:

  • html

        <?php echo form_tag_for($form, '@comments',array('class' => 'nice'));?>
    
            <?php echo $form->renderHiddenFields() ?>
            <?php echo $form->renderGlobalErrors() ?>
            <?php echo $form['_csrf_token']; ?>
            <input type="hidden" name="comments[users_id]" id="comments_users_id" value="1" />
            <input type="hidden" name="comments[tests_id]" id="comments_users_id" value="<?php echo $testId?>" />
    
    
            <?php echo $form['comment']->renderError() ?>
    
              <div class="count">remaining symbols : 250</div>
              <div class="barbox"><div class="bar"></div></div>
    
            <?php echo $form['comment']->render(array('class' => 'comments_comment')) ?>
    
            <?php  echo $form['captcha']->renderLabel(null,array('class' => 'label-login-down ')) ?>
            <?php echo $form['captcha']->renderError() ?>
            <?php echo $form['captcha']->render(array('class' => 'normal  input-text ' , 'placeholder'=>"Въведете символите")) ?>
    
            <input type="submit" name="addComment" value="Изпрати" />          
        </form> 
    
  • jQuery

    $(".comments_comment").keyup(function()
    {       
      var box=$(this).val();
      var main = box.length *100;
      var value= (main / 250);
      var count= 250 - box.length;
    
      if(box.length <= 250)
      { 
        if(box.length <=210)
        {
         $('.count').html('remaining symbols : '+count);            
        }
        else
        {          
       $('.count').html('<div class="commentAlertSymbols">remaining symbols :    '+count+'</div>'); 
        }
      $('.bar').animate(
      {
      "width": value+'%',
      }, 1);
    
    }
    else
    {
      $('.count').html('<div class="commentRedSymbols">remaining symbols : '+count+'</div>');
    }
    return false;
    });
    
4

1 回答 1

0

很高兴看到实际的表单 HTML 输出而不是所有那些 PHP 帮助函数,但我会试一试:

$('.comments_comment').keyup(function() {
    // Get the number of characters, percent used, and number left
    var $count = $('.count');
    var chars = $(this).val().length;
    var percent = (chars / 250) * 100;
    var left = 250 - chars;

    // Update the counter
    $count.html('Remaining Symbols: ' + left);

    // Add classes based on how many are left
    if (chars > 210 && chars <= 250) {
        $count.addClass('commentAlertSymbols');
    } else if (chars > 250) {
        $count.addClass('commentRedSymbols');
    }

    // Animate the bar
    $('.bar').css({
        width: chars <= 250 ? percent + '%' : '100%'
    });
});

我使代码更加干燥。另外,我将$('.bar').animate行更改为$('.bar').css,因为我没有看到在一秒钟内设置动画的意义。

您可以在http://jsfiddle.net/KjTrj/看到一个有效的 JSFiddle 。

于 2012-06-06T13:16:18.933 回答