douyiavxxh02727 2016-11-17 07:39
浏览 44
已采纳

如何在php代码之间添加jquery字数和限制

I have this code for a textarea count. It works well but once I embed it like I have done below, it doesn't work and no error is thrown. I've been on it for over 3 days now. I'll appreciate some help please.

<div class="row">

    <label for="name" class="control-label">
    <?php if(isset($data['career_objective']) && $data['career_objective']!=''){?>
          <p id="c_obj" class="text-info first " data-type="textarea" name="comments2"  onclick="return update('c_obj' ,'career_obj' ,'Career Objective'); "><?php echo $data['career_objective']; ?></p>
          <br>
          Word Count : <span id="display_count">0</span> words. Words left : <span id="word_left">50</span>
    <?php } else { ?>
          <p id="c_obj" class="text-info first " data-type="textarea" name="comments2" onclick="return update('c_obj' ,'career_obj' ,'Career Objective'); ">Career Profile and Work objectives here. Not more than 50 words.</p>
    <?php }?>
    </label>
<div class="controls">
    <a href="#" class="btn pen c_obj1"><span class="glyphicon redcolor first" aria-hidden="true">Edit</span></a>
</div> </div>

The Jquery part

$("#c_obj").on('keyup', function() {
var words = this.value.match(/\S+/g).length;
if (words > 50) {
  // Split the string on first 200 words and rejoin on spaces
  var trimmed = $(this).val().split(/\s+/, 50).join(" ");
  // Add a space at the end to make sure more typing creates new words
  $(this).val(trimmed + " ");
  alert("You reached your limit of 50 words.");
}
else {
  $('#display_count').text(words);
  $('#word_left').text(50-words);
} });
  • 写回答

2条回答 默认 最新

  • douxun1934 2016-11-17 13:43
    关注

    From the html element below, I am pretty sure that you're using a third-party library to create a textarea element for taking a user input programmatically.

    <p id="c_obj" class="text-info first " data-type="textarea" name="comments2" ...
    

    Now, $('#c_obj').on(.. binds an event on a p tag, not the textarea element you want to check the word count. The reason could be either the textarea doesn't exist yet, or it gets created dynamically after user initiates an action.

    Solution:

    Bind an event on a body or parent element instead and delegate the keyup event to the target textarea.

    $(".parent-div").on('keyup', 'textarea', function(e) { ...
    

    The parent-div can be the form element or the closest parent element if preferred.

    See the sample code here - http://codepen.io/chainat/pen/VmmmKg

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器