2016-09-24 112 views
0

我正在研究限制标记,因此max将为5,但对于此测试,我将使用2,但是在行尾有一个额外的逗号,当尝试添加另一个逗号时标签超过最大允许值。我如何删除逗号?删除行尾的额外逗号

<body> 
     <input id="input" type="text" /> 
    </body> 

    $("#input").keypress(function(e){ 
    var value = $(this).val().replace(" ", ""); 
    var words = value.split(","); 

    if(words.length > 2){ 
     //alert("Hey! That's more than 5 words!"); 
     e.preventDefault(); 
    } 
}); 

DEMO:http://jsfiddle.net/BzN5W/2/

+0

[RTRIM在javascript]的可能的复制(http://stackoverflow.com/questions/8791394/rtrim-in-javascript) – Rasclatt

回答

1

这里,试试这个:

$("#input").keypress(function(e){ 
var value = $(this).val().replace(" ", ""); 
var words = value.split(","); 

if(words.length > 5){ 
    alert("Hey! That's more than 5 words!"); 

    $('#input').val($('#input').val().substring(0, $('#input').val().length-1)); 
     e.preventDefault(); 
} 

});

+0

如何在其下方添加另一行,以防止在前面添加更多关键字 –

+0

如何添加代码以防止在其中键入更多关键字 –

0
$("#input").keypress(function(e){ 
    var value = $(this).val().replace(" ", ""); 
    var words = value.split(","); 
    if(words.length > 5){ 
     $(this).val(value.slice(0,value.length-1)) 
     e.preventDefault(); 
    } 
}); 
0

尝试此:

$("#input").keydown(function(e){ 
 
     if(e.which === 188 && ($(this).val().match(/,/g) || []).length ==4){ 
 
     e.preventDefault(); 
 
     } 
 
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<body> 
 
    <input id="input" type="text" /> 
 
</body>