垂直条形图与验证

时间:2015-06-08 13:22:37

标签: javascript html validation charts

我更改了代码abit,因为我想在代码中进行一些验证。在酒吧之前有"%"在它上面和键入的名称下,现在如果我输入2个参与者,它会创建4个条而不是2.在名称所在的位置是"未定义" %应该是NaN%。有人知道错误在哪里吗?

<head>
    <title>examAnalysis</title>
    <meta http-equiv="content-type" content="text/html; charset=utf-8" />
    <style type="text/css">
    div {
        float: left; margin-right: 10px;
    }
    div p { 
        text-align: center;
    }
    </style>
    <script type="text/javascript">
var participant = [];
var maxPoints = 200;
var barWidth = 50;

function gatherData() {
    var name;
    var points;
    while (name = window.prompt('Please enter the name of the participant:')) {
        name = name.replace(/\s+/g, '')
    if ((/[^A-Z\s\-\']/gi.test(name)) || (name == '')) {
        alert ('You must enter a valid name! ');
    } else {
        participant.push({name: name});

        while(points = window.prompt('Please enter the achieved points of the participant:')) {
        points = parseInt(points, 10); 
        if ((/[^0-9\s\-\']/gi.test(points)) || (points == '')) {
            alert ('You must enter a valid number! ');
        } else {
            participant.push({points: points});
            break;
          }
        }  
    }
}
    createChart();
};

function createChart ()
    {
        var i = 0;
        var len = participant.length;
        var bar = null;

        var container = document.getElementById('chart');
        container.innerHTML='';

        while (i < len)
        {

            bar = document.createElement('div');
            bar.style.width = barWidth + 'px';
            bar.style.backgroundColor = getRandomColor();
            bar.style.float = 'left';
            bar.style.marginRight = '10px';

            bar.style.height = ((participant[i].points / maxPoints) * 200) + 'px';
            bar.style.marginTop = 200 - parseInt(bar.style.height) + 'px';
            percent = ((participant[i].points / maxPoints) * 100) + '%';    
            bar.innerHTML = ['<p style="margin-top: ' + (parseInt(bar.style.height) - 17) + 'px">', percent, '<br />', participant[i].name, '</p>'].join('');

            container.appendChild(bar);

            i = i + 1;
        }
    };

function getRandomColor () {
    return ['rgb(', Math.floor(Math.random() * 255), ', ', Math.floor(Math.random() * 255), ', ', Math.floor(Math.random() * 255), ')'].join('');
 };
    </script>
</head>

<body>
    <button onclick="gatherData()">Add Participant</button>
    <h4>Chart</h4>
    <div id="chart"></div>
</body>

1 个答案:

答案 0 :(得分:1)

试试这个:

Project.find(5).technologies