2012-02-21 98 views
0

我通過onkey up事件添加兩個文本框值。每次輸入數據,都會被提交到服務器,然後結果將由json返回。我得到一個由json文本框(通過一個組合的onchange事件)和另一個文本框已經存在於HTML中,當我改變第二個文本框中的數據(在HTML中),然後總計算,但是當我改變數據第一個文本框(在JavaScript中),那麼總數不計算?我哪裏錯了?第一個和第二個文本框具有相同的類submitme從json服務器端返回金額

$(document).ready(function() { 
$(".submitme").keyup(function() { 
     $.getJSON('total.jsp', { 
     firsttextboxname: jQuery("#firsttextbox").val(), secondtextboxname: 
jQuery("#secondtextbox").val() 
     }, function (responseData) { 
      var total = responseData.sum; 
       $("#thirdtextbox").val(total);// displays total 
    }); 
}); 


$("#combo").change(function() { 
     $.getJSON('combo.jsp', { 
      comboboxname: this.value 
     }, function (responseData) { 
      // returns a text box (first text box) 
    $("#adiv").empty().append("<input type='text' class='submitme' id='firsttextbox' name='firsttextboxname'/>"); 

    }); 

}); 
}); 

HTML

<div id="adiv"> 
// getting first text box here 
</div> 
//second text box whose data is also taken along with first text box each time 

<input type="text" id="secondtextbox" class="submitme" name="secondtextboxname"/>// taking value from this text box to calculate sum 

<input type="text" id="thirdtextbox"/>// auto filling sum here 

服務器端(total.jsp)

String a=request.getParameter("firsttextboxname");// getting first text box name 
String b=request.getParameter("secondtextboxname");/ getting second text box name 

int c=Integer.parseInt(a);// converting to integer 
int d=Integer.parseInt(b);//converting to integer 

int e=c+d;// calculating total 

JSONObject jsonObj= new JSONObject(); 

jsonObj.put("sum",e);// sending sum to client side 

response.setContentType("application/json"); 
response.getWriter().write(jsonObj.toString()); 

回答

3

當您異步添加組合框(或任何元素)時,它不會獲得鍵入事件綁定。你必須使用.live()像這樣:

$(".submitme").live("keyup", function() { 
    // stuff 
}); 

jQuery documentation以瞭解如何.live()的作品。

+0

是的,它做到了訣竅 – Phillipa 2012-02-21 12:42:02

+0

但是當第一個文本框變爲空然後總和仍然在那裏沒有自動清除爲什麼?如何清除文本框時清除總數? – Phillipa 2012-02-21 12:43:36

+0

使用jQuery'.on()'如果您使用的是jQuery1.7.1 + – 2012-02-21 16:11:39

0

我看來像你的加入KEYUP事件在domready中的 「.submitme」 入級元素,但第一個文本框還沒有在文檔上。

將其添加到#combo的更改事件中,以使其沒有獲取分配給它的按鍵事件。

+0

好的,那麼可能的解決方案是什麼? – Phillipa 2012-02-21 12:34:56