选择选项有什么问题?

时间:2014-02-24 10:03:20

标签: javascript jquery

我只是尝试使用所选选项的值进行简单计算,但是我得到错误的结果: pickUp 9和returnTime 10,它给出no(必须是yea)

但是 pickUp时间11和returnTime 14,它给出了yea(这是正确的)所以它给出了一些特定数字和一些数字的正确结果..

这是(pickUp)选择选项:

<select id="ophalenUur" class="timePicker selectOption">
    <option value="-">Kies Tijd</option>
    <option value="8">08.00</option>
    <option value="8.5">08.30</option>
    <option value="9">09.00</option>
    <option value="9.5">09.30</option>
    <option value="10">10.00</option>
    <option value="10.5">10.30</option>
    <option value="11">11.00</option>
    <option value="11.5">11.30</option>
    <option value="12">12.00</option>
    <option value="12.5">12.30</option>
    <option value="13">13.00</option>
    <option value="13.5">13.30</option>
    <option value="14">14.00</option>
    <option value="14.5">14.30</option>
    <option value="15.">15.00</option>
    <option value="15.5">15.30</option>
    <option value="16">16.00</option>
    <option value="16.5">16.30</option>
    <option value="17">17.00</option>
    <option value="17.5">17.30</option>
    <option value="18">18.00</option>
    <option value="18.5">18.30</option>
    <option value="19">19.00</option>
    <option value="19.5">19.30</option>
    <option value="20">20.00</option>
</select> 

和js:

var pickUp = 0;
var returnTime =0; 

$('#ophalenUur').change(function() {
    pickUp = $('#ophalenUur option:selected').val();
    $('.pickUp').text("PickUp: " + pickUp);
});

$('#inleverenUur').change(function() {
    returnTime = $('#inleverenUur option:selected').val();
    $('.returntime').text("return: " + returnTime);

    if(returnTime > pickUp){ alert("yea");
    } else { alert("no");  }
});

小提琴:http://jsfiddle.net/jLAaq/27/

这里有什么问题?我正在寻找几个小时,我看不到:/

3 个答案:

答案 0 :(得分:2)

因为你正在进行字符串比较

var pickUp = 0;
var returnTime = 0;
var totalExtra = 0;

$('#ophalenUur').change(function () {
    //conver the value string to number by prfixing it with + or you can use parseFloat(this.value)
    pickUp = +this.value;
    $('.pickUp').text("PickUp: " + pickUp);
});

$('#inleverenUur').change(function () {
    returnTime = +this.value;
    $('.returntime').text("return: " + returnTime);

    if (returnTime > pickUp) {
        alert("yea");
    } else {
        alert("no");
    }
});

演示:Fiddle

答案 1 :(得分:1)

我认为原因可能是returnTime而pickUp是字符串。所以“9”&gt;“10”。 尝试使用parseFloat函数来解析returnTime和pickUp。

答案 2 :(得分:1)

您将整数作为字符串进行比较。您可以使用parseFloat方法

<强> Demo Link

<强> CODE:

var pickUp = 0;
var returnTime =0; 
var totalExtra = 0;

$('#ophalenUur').change(function() {
pickUp = $('#ophalenUur option:selected').val();
    $('.pickUp').text("PickUp: " + pickUp);
});

$('#inleverenUur').change(function() {
returnTime = $('#inleverenUur option:selected').val();
    $('.returntime').text("return: " + returnTime);
 if(parseFloat(returnTime) > parseFloat(pickUp)){
       alert("yea");
   }else{
    alert("no");           
  }
});