2016-02-16 71 views
1

所以我想jQuery Mobile的返回NaN

$(function() { 
 
    convertPrice = function() { 
 
    var myAnswer, myVal, myRate; 
 
    myVal = $('#slider1').val(); 
 
    myRate = $('#rate').val(); 
 
    myVal = parseFloat(myVal); // convert string type 
 
    myAnswer = myVal * myRate; 
 
    $('#Answer').val(myAnswer); 
 

 
    } 
 

 
    $("#convertButton").click(convertPrice); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script> 
 

 
<div data-role="fieldcontain"> 
 

 
    <label for="R">Cost Per Person:</label> 
 
    <input type="text" value="$990" name="rate" id="rate" readonly /> 
 
</div> 
 
<label for="slider">Number of People Going?:</label> 
 
<input type="range" name="slider" id="slider1" value="1" min="1" max="30" /> 
 
</div> 
 
<input type="button" value="Convert" id="convertButton" /> 
 

 
<div data-role="fieldcontain"> 
 
    <label for="theAnswer">Results:</label> 
 
    <input type="text" name="textInput" id="Answer" value="" readonly /> 
 
</div>

所以,當我按一下按鈕,它只是返回的喃?有什麼建議麼?

回答

0

對於費率輸入框,您已指定$ in value標記。所以它給了NaN的價值。該行代碼更改爲

$

然後,它會肯定

+0

非常感謝!它總是那麼小,我想念。 –

0

使用本作品,但要好得多刪除 「$」

$(function() { 
 
    convertPrice = function() { 
 
    var myAnswer, myVal, myRate; 
 
    myVal = $('#slider1').val(); 
 
    myRate = $('#rate').val(); 
 
    myRate = myRate.replace("$",""); 
 
    myVal = parseFloat(myVal); // convert string type 
 
    myAnswer = myVal * myRate; 
 
    $('#Answer').val(myAnswer); 
 

 
    } 
 

 
    $("#convertButton").click(convertPrice); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script> 
 

 
<div data-role="fieldcontain"> 
 

 
    <label for="R">Cost Per Person:</label> 
 
    <input type="text" value="$990" name="rate" id="rate" readonly /> 
 
</div> 
 
<label for="slider">Number of People Going?:</label> 
 
<input type="range" name="slider" id="slider1" value="1" min="1" max="30" /> 
 
</div> 
 
<input type="button" value="Convert" id="convertButton" /> 
 

 
<div data-role="fieldcontain"> 
 
    <label for="theAnswer">Results:</label> 
 
    <input type="text" name="textInput" id="Answer" value="" readonly /> 
 
</div>

0

由於在前面的回答中提到$符號是問題。你可以刪除$符號它將起作用。如果你想保留這個符號,那麼usi ng regex您可以在計算時刪除該標誌

var myAnswer, myVal, myRate; 
myVal = $('#slider1').val(); 
myRate = $('#rate').val(); 
myVal = parseFloat(myVal); // convert string type 
myRate = parseFloat(myRate.replace(/[^0-9\.-]+/g, "")); // here before convserting we need to use regex to replace $ with "" 
myAnswer = myVal * myRate; 
$('#Answer').val(myAnswer);