我想阻止退格键并单击删除按钮以从文本框中删除$.
例如:如果我的文本框值是$ 10.00,我应该只能删除数字而不是$和点。

 <h:dataTable id="Dtable" var="item"
 value="#{bean.list}">
 <h:column>
 <h:inputText id="txt1" value="#{item.Amount1}" onkeypress=" return isMoney(this,event)"></h:inputText>
 </h:column>
 </h:dataTable>


这就是我只允许数字,$和点的方式。在文本框中输入。

 function isMoney(thisObj,evt)
  {
     var charCode = (evt.which) ? evt.which : event.keyCode
     if(charCode == 46 || charCode == 36) // decimal pt or $
    return true;
     if (charCode > 31 && (charCode < 48 || charCode > 57))
        return false;
     return true;
  }


注意:行数可能会变化,因此我无法使用id来获取特定的文本框。

最佳答案

如果您的字段是动态添加的,则必须使用event delegation
由于在此文档中我不知道向页面中添加元素的代码,因此您会找到一个将文本字段添加至body标签的按钮
如您所见,脚本甚至可以与动态添加的元素一起使用
鉴于我的“宝贵时间”,请不要忘记在我的答复中标记为绿色;)谢谢。

<!DOCTYPE HTML>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
(function ($, undefined) {
    $.fn.getCursorPosition = function() {
        var el = $(this).get(0);
        var pos = 0;
        if('selectionStart' in el) {
            pos = el.selectionStart;
        } else if('selection' in document) {
            el.focus();
            var Sel = document.selection.createRange();
            var SelLength = document.selection.createRange().text.length;
            Sel.moveStart('character', -el.value.length);
            pos = Sel.text.length - SelLength;
        }
        return pos;
    }
})(jQuery);

$(document).ready(function(){
    $('#new').click(function(){
        $('<input type="text" value="$500.45">').appendTo('body')
    })

    $('body').on('keydown','input',function(e){
         var keycode= (e.keyCode ? e.keyCode : e.which);
         if(keycode == 8){
            var position = $(this).getCursorPosition();
            var ca=$(this).val().slice(0,position).split('');
            var x=ca[ca.length-1];
            if(x==='$'||x==='.'){e.preventDefault()};
        };
        if(keycode == 46){
            var position = $(this).getCursorPosition();
            var ca=$(this).val().slice(0,position+1).split('');
            var x=ca[ca.length-1];
            if(x==='$'||x==='.'){e.preventDefault()};
            };
        })
});

</script>

</head>

<body>
<input id="a" name="" type="text" value="$500.45">
<input name="" type="button" value="newImput" id="new">

</body>
</html>

10-05 20:42
查看更多