dosf40815 2012-06-01 15:38 采纳率: 100%
浏览 36
已采纳

使用JSON数组检查输入文本字段中的值

The problem:

I have a function that partially works and for some reason it gets stuck with the value 100. All other values work without a problem. The function compares the value of an input field with the correspondent value in a JSON array.

Scenario:

Take for instance you make the choice 3 then 1 then 1, you will end up with value 12. If you enter 100 in the input field and then move on an error will show up as indicated by the addClass(). 100 is not less than 12 and should not allow the addClass() to add the error. Where is the error here?

The HTML code:

<div id="ref" class="control-group">
    <label class="control-label">Number of references:</label>

    <div class="controls">
        <div class="input-prepend">
            <input class="input-small" id="references" name="references" type="text">
        </div>
    </div>
</div>

The array is generated by PHP and transformed to JavaScript through json_encode() according to the following:

var numbers = <?php echo json_encode($numbers); ?>;

The array:

{
    "1":{
        "1":{
            "1":"36",
            "2":"63"
        },
        "2":{
            "1":"54",
            "2":"63"
        }
    },
    "2":{
        "1":{
            "1":"60",
            "2":"105"
        },
        "2":{
            "1":"90",
            "2":"105"
        }
    },
    "3":{
        "1":{
            "1":"12",
            "2":"21"
        },
        "2":{
            "1":"18",
            "2":"24"
        }
    }
}

The jQuery code:

<script type="text/javascript">
    $(document).ready(function()
    {           
        $('#references').change(function() 
        {
            var choice1 = $('input[name=level]:checked').val();

            if (choice1 == '1') 
            {
                var choice2 = $('input[name=authors]:checked').val();
            } 
            else 
            {
                var choice2 = $('input[name=credits]:checked').val();
            }

            var number = numbers[3][choice1][choice2];

            if ($(this).val() < number) 
            {
                $('#ref').addClass('error');
            } 
            else 
            {
                $('#ref').removeClass('error');
            }
        });
    });
</script>
  • 写回答

2条回答 默认 最新

  • dpd46554 2012-06-01 15:42
    关注

    You are doing a string comparison there. In string comparision "100" < "12" = true. Try doing a number comparison like below,

    if (parseInt($(this).val(), 10) < parseInt(number, 10))
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 jupyterthemes 设置完毕后没有效果
  • ¥15 matlab图像高斯低通滤波
  • ¥15 针对曲面部件的制孔路径规划,大家有什么思路吗
  • ¥15 钢筋实图交点识别,机器视觉代码
  • ¥15 如何在Linux系统中,但是在window系统上idea里面可以正常运行?(相关搜索:jar包)
  • ¥50 400g qsfp 光模块iphy方案
  • ¥15 两块ADC0804用proteus仿真时,出现异常
  • ¥15 关于风控系统,如何去选择
  • ¥15 这款软件是什么?需要能满足我的需求
  • ¥15 SpringSecurityOauth2登陆前后request不一致