dongxian6715 2015-10-28 09:04
浏览 34
已采纳

选择字段控制字符限制

Does anyone know how to allow this character countdown to be controlled by pre-determined variables that are linked to the select field options?

var large = 300
var medium = 200
var small = 100

I appreciate any input greatly.

Example Code:

<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>

function updateCountdown() {
    var remaining = 50 - jQuery('#post').val().length;
    jQuery('#character_limit').text(remaining + ' characters remaining.');
}

jQuery(document).ready(function($) {
    updateCountdown();
    $('#post').change(updateCountdown);
    $('#post').keyup(updateCountdown);
});

</script>
<textarea id="post" cols="40" rows="3" maxlength="500"></textarea>
<div id="character_limit"></div>

<select name="product" id="product">
<option value="large">Large Product</option>
<option value="medium">Medium Product</option>
<option value="small">Small Product</option>
</select>
  • 写回答

1条回答 默认 最新

  • dqve65954 2015-10-28 09:10
    关注

    You can achieve this by firstly changing the options of the select element to have a value equal to the length required by that type of product:

    <select name="product" id="product">
        <option value="300">Large Product</option>
        <option value="200">Medium Product</option>
        <option value="100">Small Product</option>
    </select>
    

    From there you can retrieve the selected value (converting it to a number) before subtracting the number of used characters. Also note that you would also now need to update the count on the change event of the #product field. Try this:

    function updateCountdown() {
        var charLimit = parseInt($product.val(), 10)
        var remaining = charLimit - jQuery('#post').val().length;
        jQuery('#character_limit').text(remaining + ' characters remaining.');
    }
    
    var $product = $('#product');
    updateCountdown();
    $('#post, #product').change(updateCountdown);
    $('#post').keyup(updateCountdown);
    

    Example fiddle

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 安装svn网络有问题怎么办
  • ¥15 Python爬取指定微博话题下的内容,保存为txt
  • ¥15 vue2登录调用后端接口如何实现
  • ¥65 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥15 latex怎么处理论文引理引用参考文献