2013-04-11 73 views
0

我想建立一個費用計算器,爲此我需要訪問表單,我想知道我是否可以在jQuery中完成。 所以我的代碼是:如何訪問表單選擇jQuery?如何從輸入的金額中獲取「%」?

<form id="fee"> 
    <input type="text" title="fee" placeholder="Place the amount that you would like to send"/> $ 
    <input type="submit" onclick="getFee()"/> 
</form> 
<br/> 
<p id="Here will be the fee"></p> 

而且JS:

function getFee(){ 
    $("fee > input:fee"). 
} 

這裏是我的問題。我想知道如何獲取用戶在輸入中輸入的金額並添加10%的金額,然後將其打印在下面的段落中。

+0

未來,請儘量在您的問題上更加一致,並提供您正在嘗試做什麼的完整說明。 – 2013-04-11 20:33:41

回答

1

首先關閉所有,添加ID您輸入這樣

<input type="text" id="amount" 

現在得到的值是這樣的:

var amount = $("#amount").val(); 

不要使用空格在您的ID

<p id="Here will be the fee"></p> 

使用這個代替

<p id="feeOnAmount"></p> 

現在你可以添加10%的量這樣

function getFee(){ 
    var amount = parseFloat($("#amount").val()); 
    if($.isNumeric(amount)){ 
     $("#feeOnAmount").html((amount * 1.1));  
    } 
    else{ 
     $("#feeOnAmount").html("please enter a valid number"); 
    } 
} 

http://jsfiddle.net/mohammadAdil/E2rJQ/15/

+1

您可以將算術簡化爲'(金額* 1.1)' – 2013-04-11 20:30:50

+0

非常感謝!幫助我很多! 我怎麼可以澄清,用戶只輸入數字? – 2013-04-11 20:35:45

+0

你應該使用'parseFloat'而不是'parseInt'。嘗試:'parseInt(010);'。 – andlrc 2013-04-11 20:45:33

0

使用#號標識。還要爲輸入添加一個ID。 id="feeInput"

此標題不是有效的輸入標籤。

function getFee(){ 
     $("#fee > input#feeInput"). 
    } 
0

試試這個

function getFee(){ 
    var inputVal = $("#fee > input[title='fee']").val(); 
    var inputFinal = parseInt(inputVal) + (parseInt(inputVal) * .10); 

    //Change the ID of the p your appending to 
    //ID is now = "calc" 
    $("#calc").text(inputFinal); 
} 

繼承人演示:http://jsfiddle.net/Ln3RN/

0

我改變了輸出ID和選擇器。 example in jsfiddle

attribute selectors

$(document).ready(function() { 
    $("#fee")[0].onsubmit= getFee; 

}); 
function getFee(){ 
     var feeInput = $('#fee > input[title="fee"]').val(); 
     feeInput = parseInt(feeInput); 
     $('#Here_will_be_the_fee').text(feeInput*1.1); 
     return false; 
} 

getFee返回false,以便在窗體不會提交,只會觸發onsubmit事件。

相關問題