jQuery自动完成多个minLength

时间:2014-09-18 13:27:12

标签: javascript jquery

我需要检查一个数值是否来自“#lookup”字段, 如果它是数字我需要将minLength设置为5,否则它将minLength:3,

有可能吗?

<script type="text/javascript">
$(document).ready(function() {
    $( "#lookup" ).autocomplete({
        source: function(request, response) {
            $.ajax({
                url: "script.pl",
                dataType: "json",
                data: {
                    term : request.term,
                },
                success: function(data) {
                    response(data);
                    console.log(data);
                },
                error: function(response){
                    alert('Somethings broken in the AJAX return');
                }
            });
        },
        close:function(){
            this.value=''
        },
        // need to check here if a numeric value is coming from #lookup
        // if it is, I would like to set this to: minLength: 5,
        // else minLength: 3,
        minLength: 3,
        delay: 500
    });
});
</script>

2 个答案:

答案 0 :(得分:0)

这应该检查一个值,即使它最初是一个字符串,是否安全地转换为数值:

function isNumeric(n) { 
      return !isNaN(parseFloat(n)) && isFinite(n); 
}

在此处找到:http://www.neiland.net/blog/article/javascript-isnumeric/

答案 1 :(得分:0)

也许是这样的

$("#lookup").on('keyup', function(){
    var $this = $(this);
    if(isNumeric($this.val())) {
        $this.data('uiAutocomplete').options.minLength = 5
    }
})

和来自@Dpeif的isNumetic函数回答:

function isNumeric(n) { 
      return !isNaN(parseFloat(n)) && isFinite(n); 
}