7

I am having the following HTML block in my page.

<input type="text" id="fillingInput"/>
<input type="text" id="filledInput" maxlength="5"/>
<input type="button" onclick="$('#filledInput').val($('#fillingInput').val());"/>

when the button is clicked, the value of fillingInput is set as value for filledInput. But the maxlength is not considered while setting value like this. Any solution?

4

4 回答 4

4

尝试slice

<input type="button"
  onclick="$('#filledInput').val($('#fillingInput').val().slice(0,5));"/>
于 2013-08-30T10:34:25.253 回答
1

尝试这个

$(document).ready(function () {
$('#add').click(function () {
    var str = $('#fillingInput').val();
    if (str.length > 5) {
        str = str.substring(0, 5);
        $('#filledInput').val(str);
    }

   });
});
于 2013-08-30T10:37:43.543 回答
1

如果您使用的是 jQuery,您可以添加一个“valHook”,它会挂接到每个 .val() 调用中

$.valHooks.input = {
    set: function(element, value) {
        if ("maxLength" in element && value.length > element.maxLength)
            value = value.substr(0, element.maxLength);
        element.value = value;
        return true;
    }
};
于 2014-07-17T21:09:10.890 回答
1

一种方法是……删除第 5 个字符后的所有字符。使用substring()

 <input type="button" id="add" />

JS

 $('#add').click(function(){
   var str=$('#fillingInput').val();
   if(str.length > 5) {
      str = str.substring(0,5);

  }
   $('#filledInput').val(str);
 });

小提琴..

建议不要使用内联 javascript。

于 2013-08-30T10:32:23.927 回答